我需要使用條件語句以及DISTINCT
值 和GROUP BY
來收集總和。下面的例子是一個非常複雜的查詢的簡化版本。帶有條件的MySQL SUM DISTINCT
因爲真正的查詢是非常大的,我需要避免大幅重新編寫查詢。
DATA
Contracts
id advertiser_id status
1 1 1
2 2 1
3 3 2
4 1 1
一個查詢,已經接近
SELECT
COUNT(DISTINCT advertiser_id) AS advertiser_qty,
COUNT(DISTINCT id) AS contract_qty,
SUM(IF(status = 1, 1, 0)) AS current_qty,
SUM(IF(status = 2, 1, 0)) AS expired_qty,
SUM(IF(status = 3, 1, 0)) AS other_qty
FROM (
SELECT * FROM `contracts`
GROUP BY advertiser_id, id
) AS temp
目前返回
advertiser_qty contract_qty current_qty expired_qty other_qty
3 4 3 1 0
需要返回
advertiser_qty contract_qty current_qty expired_qty other_qty
3 4 2 1 0
哪裏current_qty
爲2,它是與status = 1
記錄僅DISTINCT advertiser_ids
總和與每個和功能都需要相同的修訂。
我希望有人有一個簡單的解決方案,可以插入SUM
功能。
-Thanks!
是什麼'interested'?它的一列? – 2013-03-13 20:07:00
(固定)Type-o,它應該是狀態 – 2013-03-13 20:13:01