2014-02-15 160 views
4

我的英文不是很好,但我試着解釋我的自己清楚。我需要建議。 我正在從一個表中選擇每個字段的值的總和。 和我的查詢看起來像這樣:mysql UNION查詢輸出

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 

回答

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) 
+0

你能解釋一下什麼樣的PLS'IF(BannerId = 3456,點擊次數,0))'手段?我真的不明白'0'是什麼意思?謝謝。 – Victorino

+0

@Viktorino'0'是'IF()'調用的'else'條件。你可以閱讀關於[這裏]的語法(http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_if)。 – hjpotter92

+0

感謝您的建議! – Victorino

0

嘗試使用交叉連接 - 不完全它的意圖是什麼,但是因爲你只有2個結果,它應該可以工作 - 但是你必須省略「'銷售'作爲類型」和「租金」作爲類型「投影」。

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 
+0

雖然我也很喜歡hjpotter92的回答,但我缺乏IF()語法的知識來自己做=) – deroby