Skip to content
Advertisement

Add additional column to the query output

I have the following query that is grabbing data from a table and combining all the products into one column and counting the quantity of that order.

I need to add an additional column to the output though, how can I also add 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;

This is how the original table is laid out:

l

And this is how the query outputs the results:

enter image description here

How can I add ship_date to that output?

Advertisement

Answer

It looks like ship_date is fixed for each and every order_id. If so, you can just add it to the inner and outer aggregation:

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;
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement