在查询输出中添加其他列

时间:2020-07-13 09:15:43

标签: mysql sql date count sum

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

尽管我需要在输出中添加一列,但如何添加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;

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

l

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

enter image description here

如何将ship_date添加到该输出?

1 个答案:

答案 0 :(得分: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;
相关问题