> Dear collegues,
>
[quoted text clipped - 21 lines]
>
> Any idea how to sqeeze this into a single query?
Apart from the fact that your query is syntactically not correct, one idea
might be this:
SELECT o.customer,
( SELECT DEC(SUM(i.amount)) AS gross
FROM orders AS i
WHERE YEAR(i.inv_date) = YEAR(CURRENT DATE) AND
i.customer = o.customer ) AS this_year,
( SELECT DEC(SUM(i.amount)) AS gross
FROM orders AS i
WHERE YEAR(i.inv_date) = YEAR(CURRENT DATE) - 1 AND
i.customer = o.customer ) AS prev_year
FROM orders AS o
or this:
SELECT t1.customer, t1.amount, t2.amount
FROM ( SELECT customer, DEC(SUM(amount)) AS amount
FROM orders
WHERE YEAR(i.inv_date) = YEAR(CURRENT DATE)
GROUP BY customer ) AS t1 JOIN
( SELECT customer, DEC(SUM(amount)) AS amount
FROM orders
WHERE YEAR(i.inv_date) = YEAR(CURRENT DATE) - 1
GROUP BY customer ) AS t2 ON
( t1.customer = t2.customer )
Or via a single scan:
SELECT customer,
DEC(SUM(CASE
WHEN YEAR(i.inv_date) = YEAR(CURRENT DATE)
THEN amount
ELSE 0
END)),
DEC(SUM(CASE
WHEN YEAR(i.inv_date) = YEAR(CURRENT DATE) - 1
THEN amount
ELSE 0
END))
FROM orders
GROUP BY customer

Signature
Knut Stolze
DB2 Information Integration Development
IBM Germany
Bernd Hohmann - 29 Dec 2005 22:56 GMT
>> Any idea how to sqeeze this into a single query?
>
> Apart from the fact that your query is syntactically not correct, one idea
> might be this:
Well, SQL isn't my mother tongue :-)
Thanks for your help, I'll try to transform your examples into the final
query and query visual explain how the're performing.
Bernd