2013-03-13 326 views
3

我需要使用條件語句以及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!

+0

是什麼'interested'?它的一列? – 2013-03-13 20:07:00

+0

(固定)Type-o,它應該是狀態 – 2013-03-13 20:13:01

回答

3

試試這個

SELECT 
    COUNT(DISTINCT advertiser_id) AS advertiser_qty, 
    COUNT(DISTINCT id) AS contract_qty, 
    (select count(distinct advertiser_id) from contracts where status =1 
    ) 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 

DEMO HERE

編輯:

你可以看這個沒有再選擇。

SELECT COUNT(DISTINCT advertiser_id) AS advertiser_qty, 
     COUNT(DISTINCT id) AS contract_qty, 
     COUNT(DISTINCT advertiser_id , status = 1) 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 

DEMO HERE

+0

對不起,這不起作用,因爲我的意思是有興趣成爲地位。 – 2013-03-13 20:16:29

+0

更改爲狀態 – 2013-03-13 20:19:04

+0

看我更新的答案我這你看看 – 2013-03-13 20:29:50