Skip to content
Advertisement

SQL subquery with aggregate value

Sorry for the vague title, I’m a little lost here. I have two simple aggregate SQL queries, but I struggle to combine them in a functional way (likely through a subquery) in IBM DB2. Main goal is to run COUNT function in INVOICES table – but with the starting date based on a subquery MAX aggregate result.

But as noted, I don’t want a.invdate to be fixed (20200101). I’d need to run MAX function in SERVICE table and use its result as the paramenter for a.invdate. Is there a reasonable way to do this?

So, looking to count invoices for each Item since the last service date (matching it’s own parameters). Obviously, a.item = b.item here.

Advertisement

Answer

If I followed you correctly, you can join, or use a correlated subquery:

This should be an efficient approach, provided that you have an index on services(item, servtype).

Alternatively, here is the join approach:

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement