【问题标题】:Add additional column to the query output向查询输出添加附加列
【发布时间】:2020-11-02 11:12:45
【问题描述】:

我有以下查询,它从表中获取数据并将所有产品组合到一列中并计算该订单的数量。

我需要在输出中添加一个额外的列,我怎样才能添加ship_date

select order_id, group_concat(product_id, ' - ', cnt separator ', ') as products, sum(cnt) as total
from (select order_id, product_id, count(*) as cnt
      from tt_order_items
      group by order_id, product_id
     ) op
group by order_id;

这是原始表格的布局方式:

这就是查询输出结果的方式:

如何将ship_date 添加到该输出?

【问题讨论】:

  • 请显示您想要的结果。

标签: mysql sql date count sum


【解决方案1】:

看起来像ship_date 对于每个order_id 都是固定的。如果是这样,您可以将其添加到内部和外部聚合中:

select 
    order_id, 
    group_concat(product_id, ' - ', cnt separator ', ') as products, 
    sum(cnt) as total,
    ship_date
from (
    select order_id, product_id, count(*) as cnt, ship_date
    from tt_order_items
    group by order_id, product_id, ship_date
) op
group by order_id, ship_date;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    相关资源
    最近更新 更多