我需要使用条件语句以及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 = 1
for only的记录总和DISTINCT advertiser_ids
,每个求和函数都需要相同的修复。
我希望有人有一个可以插入SUM
功能的简单解决方案。
-谢谢!!