向查询输出中添加其他列

jjjwad0x  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(284)

我有下面的查询,它从一个表中获取数据,并将所有产品组合到一列中,计算该订单的数量。
我需要向输出中添加一个额外的列,但是如何也添加 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 到那个输出?

gmol1639

gmol16391#

看起来像 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;

相关问题