SQL:一次查询依靠不同的情况

时间:2018-09-03 00:39:39

标签: mysql sql

例如,我有一张表记录了用户查看和下载文件的活动,

file_id    user    activity
      2     Tim        view
      1     Ron        view
      1     Ron        view
      2     Tim    download
      2     Ron        view
      1     Ron        view
      2     Ron    download

理想的选择结果是这样的

file_id    viewed_by    views    downloaded_by    downloads
      1            1        3                0            0
      2            2        2                2            2

我能做的就是在2个独立的查询中获取视图数据并下载数据,

COUNT(*), COUNT(DISTINCT user)
FROM table
WHERE activity = 'view'
GROUP BY file_id

(and then do another query for downloads)

是否可以在单个查询或子查询中执行此操作?

1 个答案:

答案 0 :(得分:1)

您可以尝试使用条件聚合来仅对行进行计数,其中活动使用CASE表达式匹配视图或下载。

SELECT file_id,
       count(DISTINCT CASE activity
                        WHEN 'view' THEN
                          user
                      END) viewed_by,
       count(CASE activity
               WHEN 'view' THEN
                 user
             END) views,
       count(DISTINCT CASE activity
                        WHEN 'download' THEN
                          user
                      END) downloaded_by,
       count(CASE activity
               WHEN 'download' THEN
                 user
             END) downloads
       FROM elbat
       GROUP BY file_id;