3

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

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

数据

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 = 1for only的记录总和DISTINCT advertiser_ids,每个求和函数都需要相同的修复。

我希望有人有一个可以插入SUM功能的简单解决方案。

-谢谢!!

4

1 回答 1

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

在这里演示

编辑:

你可以在没有子选择的情况下寻找这个。

 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

在这里演示

于 2013-03-13T20:04:55.740 回答