SQL 2" group by"在同一个查询中

时间:2014-05-12 06:38:09

标签: mysql sql group-by

我们有表格来跟踪用户访问过的产品页面。

product_tracking
____________________
id  user_id  product
1   1        A
2   1        B
3   2        A 
4   1        A

我知道我们可以使用group by user_id和group_by product但我需要两者。

预期结果:

result_table 
____________________________
user_id      A     B    C 
  1          2     1    0
  2          1     0    0 

任何想法如何合并2组?

2 个答案:

答案 0 :(得分:2)

你可以这样做:

SELECT
    product_tracking.user_id,
    SUM(CASE WHEN product_tracking.product='A' THEN 1 ELSE 0 END) AS A,
    SUM(CASE WHEN product_tracking.product='B' THEN 1 ELSE 0 END) AS B,
    SUM(CASE WHEN product_tracking.product='C' THEN 1 ELSE 0 END) AS C
FROM
    product_tracking
GROUP BY
    product_tracking.user_id

答案 1 :(得分:1)

使用sum(...)的替代方法是使用count(...):

SELECT product_tracking.user_id, COUNT(CASE WHEN product_tracking.product='A' THEN 1 END) AS A, COUNT(CASE WHEN product_tracking.product='B' THEN 1 END) AS B, COUNT(CASE WHEN product_tracking.product='C' THEN 1 END) AS C FROM product_tracking GROUP BY product_tracking.user_id