My data is as follows:
|cat |subcat |amount| --------------------- |A |1 |123 | |A |2 |456 | |B |1 |222 | |B |2 |333 |
In the first case, I need to summarize cat and subcat. Easy:
SELECT cat, subcat, sum(amount) FROM data GROUP BY cat, subcat
Further, I have a more complicated requirement, when for some cats the amount should be โpressedโ into this subcard. This can be saved in another config
table:
|cat |subcat| ------------- |B |1 |
This tells me that for all cat='B'
lines, the sum should be treated as subcat=1
. Also, where cat='B' AND subcat <> 1
sum should be specified as zero. In other words, I need the result:
|cat |subcat|amount| |A |1 |123 | |A |2 |456 | |B |1 |555 | |B |2 |0 |
I can not update the data table. Of course, I can SELECT ... INTO
in proc and correct the data there, but I wonder if this can be done in one hit.
I can get close to:
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 does not fulfill my second requirement to show cat:B, subcat:2
as zero.
Is it possible?
I use Sybase IQ 12.5 (i.e. old T-SQL, but has a case
, which I suspect might be useful)