【问题标题】:Group rows by Id and concatenate month & order_count as columns?按 Id 分组行并将月份和 order_count 连接为列?
【发布时间】:2021-12-29 20:29:18
【问题描述】:

目前我有一个订单表,格式为每月一行:

id order_month order_count order_sum
111 2021-07 5 50
111 2021-08 10 50
111 2021-09 1 100
222 2021-07 8 80
222 2021-08 2 50
222 2021-09 1 80

有没有办法格式化 SQL 查询,以便输出每个 id 有 1 行,而其他值作为列添加?例如。类似:

id 2021-07_order_count 2021-07_order_sum 2021-08_order_count 2021-08_order_sum 2021-09_order_count 2021-09_order_sum
111 5 50 10 50 1 100
222 8 80 2 50 1 80

我想我很接近以下查询:

SELECT 
    merchant_id,
    (CASE WHEN order_month = '2021-07' THEN order_count ELSE 0 END) as '2021-07-orderCount',
    (CASE WHEN order_month = '2021-07' THEN order_sum ELSE 0 END) as '2021-07-orderSum',
    (CASE WHEN order_month = '2021-08' THEN order_count ELSE 0 END) as '2021-08-orderCount',
    (CASE WHEN order_month = '2021-08' THEN order_sum ELSE 0 END) as '2021-08-orderSum',
    (CASE WHEN order_month = '2021-09' THEN order_count ELSE 0 END) as '2021-09-orderCount',
    (CASE WHEN order_month = '2021-09' THEN order_sum ELSE 0 END) as '2021-09-orderSum'
FROM orders
ORDER BY id

它正在创建一个单独的列并在每一列中放置正确的值。

但是,当我尝试按 Id 分组时,它只显示第一个结果:

谢谢。

【问题讨论】:

    标签: sql sqlite group-by max conditional-aggregation


    【解决方案1】:

    你需要条件聚合:

    SELECT id,
           MAX(CASE WHEN order_month = '2021-07' THEN order_count ELSE 0 END) `2021-07-orderCount`,
           MAX(CASE WHEN order_month = '2021-07' THEN order_sum ELSE 0 END) `2021-07-orderSum`,
           MAX(CASE WHEN order_month = '2021-08' THEN order_count ELSE 0 END) `2021-08-orderCount`,
           MAX(CASE WHEN order_month = '2021-08' THEN order_sum ELSE 0 END) `2021-08-orderSum`,
           MAX(CASE WHEN order_month = '2021-09' THEN order_count ELSE 0 END) `2021-09-orderCount`,
           MAX(CASE WHEN order_month = '2021-09' THEN order_sum ELSE 0 END) `2021-09-orderSum`
    FROM orders
    GROUP  BY id
    ORDER BY id;
    

    请参阅demo

    【讨论】:

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