带有条件的MySQL SUM DISTINCT

时间:2013-03-13 19:59:59

标签: mysql if-statement group-by sum distinct

我需要使用条件语句和DISTINCT值来收集总和 多个GROUP BY。下面的示例是一个更复杂的查询的简化版本。

因为真正的查询非常大,所以我需要避免大幅重写查询。

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 !!

1 个答案:

答案 0 :(得分: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