2015-10-16 34 views
0

獲取不同值的計數成單排蜂巢

userid, productid, timestamp 
1, 1, 2015-10-01 08:15:59 
1, 2, 2015-10-01 08:16:59 
2, 1, 2015-10-01 08:18:59 
3, 1, 2015-10-01 08:19:59 
1, 3, 2015-10-01 08:20:59 
2, 1, 2015-10-01 08:21:59 

我期望的輸出如下表是大致如下......

user, product1Count, product2Count, product3Count 
1, 1, 1, 1 
2, 2, 0, 0 
3, 1, 0, 0 

我已經得到了到目前爲止。但我不確定如何將這張桌子放平,並將其平鋪成每個用戶的一行。

查詢:

Select user_id, product_id, count(*) 
from masampleinput 
group by user_id, product_id 

輸出:

User, product, count 
1, 1, 1 
1, 2, 1 
1, 3, 1 
2, 1, 2 
3, 1, 1 

回答

1

希望下面的查詢可以幫助你:

select userid, 
MAX(CASE WHEN productid = 1 THEN count ELSE null END) as product1count, 
MAX(CASE WHEN productid = 2 THEN count ELSE null END) as product2count, 
MAX(CASE WHEN productid = 3 THEN count ELSE null END) as product3count 
from 
(Select user_id, product_id, count(*) 
from masampleinput 
group by user_id, product_id) 
GROUP BY userid 
+0

你可能意味着把'的0'代替'null'您'CASE'語句。 – gobrewers14

+0

嗯是的....... – madhu

+0

我有50個產品,這對於很多人來說似乎不是一個好方法......我也有4個不同的時間範圍,我想加入... –