Mysql UNION query output

my english is not very good, but I'm trying to explain my self-evidence. I need an advice. I select from one table the sum of the values ​​of each field. and my request looks like this:

SELECT * FROM
(
 SELECT SUM(Clicks) AS  sales , 'sales' as type
 FROM ClicksPerDay
 WHERE BannerID = 3456

 UNION

 SELECT SUM(Clicks) AS  rent, 'rents' as type
 FROM ClicksPerDay
 WHERE BannerID = 3457
) total

which I have:

sales | type
 23   | rents
 26   | sales

and I need it like this:

 sales | rents
   26  |  23 
+4
source share
3 answers

Try the following:

SELECT
    SUM( IF(BannerId = 3456, Clicks, 0) ) AS  sales,
    SUM( IF(BannerId = 3457, Clicks, 0) ) AS  rents
FROM ClicksPerDay
WHERE BannerID IN (3456, 3457)
+4
source

Like this:

SELECT sales = SUM(sales), rent = SUM(clicks) FROM
(
 SELECT SUM(Clicks) AS  sales , 0 as rent
 FROM ClicksPerDay
 WHERE BannerID = 3456

 UNION ALL

 SELECT 0 as sales, SUM(Clicks) AS  rent
 FROM ClicksPerDay
 WHERE BannerID = 3457
) total
+1
source

Try using a cross-connection - not quite what it is intended for, but since you only have 2 results, it should work, but you should omit sales as a type and annuities as a projection type.

0
source

Source: https://habr.com/ru/post/1527087/


All Articles