以Group By子句的条件聚合。

时间:2021-05-14 22:30:03

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

我试着用HiveQL做这个,但我不知道如何在SQL中做到这一点。表结构如下:

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 个解决方案

#1


2  

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

演示

#1


2  

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

演示