Andrew Benton
Andrew Benton

Reputation: 343

SQL - Count( ) issue

I have a table with a charge/credit column:

Item | PriceVal | CostVal | CHARGE_CODE
1        5             3         CH
2        8             5         CH
1       -5            -3         CR
3        7             1         CH
4       15            10         CH
1        5             3         CH

I've got the query I need to get the NET price and cost, but I'm also interested in the NET charges. Right now I have:

SELECT Item, SUM(PriceVal), SUM(CostVal)
FROM Table
GROUP BY Item

How do I get another column with the value

COUNT(SUM(CHARGE_CODE=CH)-SUM(CHARGE_CODE=CR))

I'm at a loss.

Upvotes: 2

Views: 1093

Answers (3)

Ryan Guill
Ryan Guill

Reputation: 13916

count() is going to count one for every value thats not null, so I don't think thats exactly what you want. Take the count out and just take the

sum(case when charge_code = CH then costval else 0 end) 
- sum(case when charge_code = 'CR' then costval else 0 end)

Upvotes: 8

paxdiablo
paxdiablo

Reputation: 882656

Since you have the dollar values entered as negatives in the table already, you can use the simple formula:

select
    Item,
    sum(PriceVal),
    sum(CostVal),
    sum(PriceVal-CostVal)
from Table
group by Item

I don't believe you should be subtracting the credit items as they're already negative.

If you really do want want the net count of transactions:

select
    Item,
    sum(PriceVal),
    sum(CostVal),
    sum(case when charge_code = 'CH' then 1 else 0 end) -
        sum(case when charge_code = 'CR' then -1 else 0 end)
from Table
group by Item

or, if there are only two charge codes, substitute:

sum(case when charge_code = 'CH' then 1 else -1 end)

for the last column.

Upvotes: 2

Draemon
Draemon

Reputation: 34729

Not 100% sure what you want, but you can count only certain rows like this:

SELECT COUNT(IF(CHARGE_CODE=CH,1,NULL)) ...

And similarly sum certain values from certain rows like this:

SELECT SUM(IF(CHARGE_CODE=CH,PriceVal,0)) ...

Upvotes: 0

Related Questions