Conditional aggregate with Group By clause

这一生的挚爱 提交于 2019-12-12 04:55:27

问题


I'm trying to do this with HiveQL but I don't know how to do this in SQL neither. Table structure as follows:

id1    id2    category  
123    abc    1
123    def    1
123    def    2
456    abc    1
123    abc    1
123    abc    2
...  

I'd like to write a query that outputs:

key           count     category1count    category2count
123-abc        3               2                 1
123-def        2               1                 1
456-abc        1               1                 0

So far I've got this:

SELECT concat( concat(id1,'-'), id2), count(*) , 
count( SELECT * WHERE buyingcategory = 1 ??? ) , 
count( SELECT * WHERE buyingcategory = 2 ??? ) 
FROM table 
GROUP BY concat( concat(id1,'-'), id2)

回答1:


try this

 SELECT concat(id1,'-', id2) `key`, count(*) , 
 sum( case when category = 1 then 1 else 0 end) category1count , 
 sum( case when category = 2 then 1 else 0 end) category2count
 FROM table1 
 GROUP BY concat(id1,'-', id2)

DEMO HERE



来源:https://stackoverflow.com/questions/17982970/conditional-aggregate-with-group-by-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!