Home  >  Q&A  >  body text

Is it possible to group by column via join?

select tc.UIDPK,
count(torder.status) as total
from TCUSTOMER tc
inner join TORDER torder on tc.UIDPK=torder.CUSTOMER_UID
where tc.UIDPK=490000;

The above query works fine for me. But the status can be IN_PROGRESS, FAILED, ON_HOLD

How do I write a query that returns a status count like tc.UIDPK, total orders, IN_PROGRESS orders, total orders-IN_PROGRESS orders. I tried the below but didn't work

select tc.UIDPK,
count(torder.status) as total,
count(torder2.status) as inprogress,
count(torder.status)-count(torder2.status) as remaining
from TCUSTOMER tc
inner join TORDER torder on tc.UIDPK=torder.CUSTOMER_UID
left join TORDER torder2 on tc.UIDPK=torder2.CUSTOMER_UID and torder2.status in('IN_PROGRESS')
where tc.UIDPK=490000;

P粉702946921P粉702946921386 days ago544

reply all(1)I'll reply

  • P粉019353247

    P粉0193532472023-09-10 00:01:39

    No need to connect multiple times, use SUM.

    try

    select tc.UIDPK,
           COUNT(torder.status) as total,
           SUM(torder.status = 'IN_PROGRESS') as inprogress,
           COUNT(torder.status) - SUM(torder.status = 'IN_PROGRESS') as remaining
    from TCUSTOMER tc
    inner join TORDER torder on tc.UIDPK=torder.CUSTOMER_UID
    where tc.UIDPK=490000
    group by tc.UIDPK;

    reply
    0
  • Cancelreply