jeudi 15 mai 2014

MySQL - conditionnelle totale avec la clause Group By - Stack Overflow


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)



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



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)


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


0 commentaires:

Enregistrer un commentaire