我的日志表看起来像这样
rpt_id | shipping_id | shop_id | status | create_time
-------------------------------------------------------------
1 | 1 | 600 | 1 | 2013-12-01 01:06:50
2 | 1 | 600 | 0 | 2013-12-01 01:06:55
3 | 1 | 600 | 1 | 2013-12-02 10:00:30
4 | 2 | 600 | 1 | 2013-12-02 10:00:30
5 | 1 | 601 | 1 | 2013-12-02 11:20:10
6 | 2 | 601 | 1 | 2013-12-02 11:20:10
7 | 1 | 601 | 0 | 2013-12-03 09:10:10
8 | 3 | 602 | 1 | 2013-12-03 13:15:58
我想使用单个查询使其看起来像这样
shipping_id | total_activate | total_deactivate
-----------------------------------------------
1 | 2 | 2
2 | 2 | 0
3 | 1 | 0
我该如何查询?
注意:
你们可以建议我如何进行查询吗?谢谢你的帮助:D
答案 0 :(得分:1)
试试这个:
select shipping_id,
sum(case when status=1 then 1 else 0 end) as total_activate,
sum(case when status=0 then 1 else 0 end) as total_deactivate
from (select distinct shipping_id,
shop_id,
status
from test) a
group by shipping_id
order by shipping_id
在小提琴中查看:http://sqlfiddle.com/#!15/f15fd/4
我没有在查询上添加日期,因为它对结果并不重要。
答案 1 :(得分:1)
非常感谢...我也已经知道了,你也可以这样做...... thx
SELECT
shipping_id,
COUNT(DISTINCT CASE WHEN status = 1 THEN shop_id END) AS total_activate,
COUNT(DISTINCT CASE WHEN status = 0 THEN shop_id END) AS total_deactivate
FROM
test
GROUP BY
shipping_id
ORDER BY
shipping_id