【问题标题】:SQL Query with nested queries, group by, and count具有嵌套查询、分组依据和计数的 SQL 查询
【发布时间】:2012-06-04 19:56:50
【问题描述】:

表格:日期、用户、订单类型。

order_type 是 4 个值的枚举:音乐、书籍、电影、艺术。

我需要一个返回总订单数和按用户分组的每个订单类型的计数的查询:

user, total, music, movies, books, art
--------------------------------------
Adam, 10, 5, 2, 3, 0
Smith, 33, 10, 3, 15,2
mary, 12,6,1,3,2
...

【问题讨论】:

    标签: mysql sql


    【解决方案1】:
    SELECT   user,
             COUNT(*)                 AS total,
             SUM(order_type='music')  AS music,
             SUM(order_type='movies') AS movies,
             SUM(order_type='books')  AS books,
             SUM(order_type='art')    AS art
    FROM     my_table
    GROUP BY user
    

    【讨论】:

      【解决方案2】:
      select user, count(*) as total, 
          sum(case when order_type = 'music' then 1 else 0) end as music,
          sum(case when order_type = 'movies' then 1 else 0) end as movies,
          sum(case when order_type = 'books' then 1 else 0) end as books,
          sum(case when order_type = 'art' then 1 else 0) end as art
      from t
      group by user
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多