My data looks like this:
|cat |subcat |amount|
---------------------
|A |1 |123 |
|A |2 |456 |
|B |1 |222 |
|B |2 |333 |
In the first case, I need to sum by cat and subcat. Easy:
SELECT cat, subcat, sum(amount) FROM data GROUP BY cat, subcat
Next, I have a more sophisticated requirement where for certain cats, the amount should be "pushed" into a given subcat. This can be stored in another config
table:
|cat |subcat|
-------------
|B |1 |
This tells me that for all cat='B'
rows, the amount should be treated as a subcat=1
. Furthermore, where cat='B' AND subcat <> 1
the amount should be reported as zero. In other words, the result I need is:
|cat |subcat|amount|
|A |1 |123 |
|A |2 |456 |
|B |1 |555 |
|B |2 |0 |
I cannot update my data table. Of course I can SELECT ... INTO
in a proc and fix the data there, but I'm wondering if it can be done in one hit.
I can get pretty close with:
SELECT data.cat,
ISNULL(config.subcat, data.subcat),
SUM(amount)
FROM data
LEFT OUTER JOIN config ON (data.cat = config.cat)
GROUP BY data.cat, ISNULL(config.subcat, data.subcat)
...but fails my second requirement to show cat:B, subcat:2
as zero.
Is it possible?
I'm using Sybase IQ 12.5 (i.e. old T-SQL, but is has the case
statement, which I suspect might be useful)