mysql UNION查询输出

时间:2014-02-15 13:06:25

标签: mysql sql

我的英语不是很好,但我试着解释清楚。我需要建议。 我从一个表中选择每个字段的值的总和。 我的查询如下:

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

我的输出是:

sales | type
 23   | rents
 26   | sales

我需要这样:

 sales | rents
   26  |  23 

3 个答案:

答案 0 :(得分:4)

尝试以下方法:

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

答案 1 :(得分:1)

像这样:

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

答案 2 :(得分:0)

尝试使用交叉连接 - 不完全是它的目的,但由于你只有2个结果,它应该可以工作 - 但是你必须省略“'sales'作为类型”和“'rents'作为类型”投影。