原数据:
table1
table1
uid tid state 2 1 normal 3 1 normal 4 1 warn 8 2 warn 9 2 warn 10 2 normal 12 4 warn 15 4 normal 19 5 warn 20 5 warn
需要返回的结果如下:
result1
tid normal_count warn_count 1 2 1 2 1 2 4 1 1 5 0 1
result1中的tid是table1中出现的全部tid,normal_count是table1中tid相同,state=normal出现的次数,warn_count同理
问一下用sql语句怎么样实现
解决方案
20
SELECT tid,SUM(CASE WHEN state = "normal" THEN 1 ELSE 0 END )AS normal_count, SUM(CASE WHEN state = "warn" THEN 1 ELSE 0 END )AS warn_count FROM table1 GROUP BY tid