tags:

views:

56

answers:

1

A friend has suggested I post here as I'm in need of a bit of help!

DB Layout:

**salestable**
salesorder [primary, unique] (sales order number)
salesman (salesperson id)

**salesline**
salesorder [many sales line to single salestable relationship]
saleprice (line amount)
isaccessory (0 or 1)

I'd like to, in a single select, sum sales price as a total per salesman, but also sum sales price where is accessory = 1.

The grouping and joins aren't what I'm stuck on, it's whether I can do the dual sum.

In my head it would look something like

...salesman,sum(amount) as totalsales,sum(amount where accessory=1) as accessorysales...

But obviously that would never work!

Thanks in advance! (PS, I'm very new here, be gentle...)

+5  A: 
SELECT  salesman, SUM(amount), SUM(CASE WHEN accessory = 1 THEN amount ELSE 0 END)
FROM    salestable t
JOIN    salesorder o
ON      o.salesorder = t.salesorder
GROUP BY
        salesman
Quassnoi
You slippery fish! You beat me to it. +1
Welbog
@Welbog: you didn't bind the keys, did you?
Quassnoi
@Quassnoi: Rather I was caught up in an explanation of what the `CASE` statement is for... You just jump right into the SQL without explaining it.
Welbog
@Welbog: in case of `CASE` (no pun intended), the query seems self-explanatory. Besides, as for me, forcing my way through documentation to find out how a program / query / whatever works has much more propaedeutic value than spoon-feed explanations. (This is of course when people ask for solutions, not for explanations).
Quassnoi
Thank you people, you are all glorious.@Quassnoi, you're right, I no longer need to think for myself (I'm joking!) Case is exactly what I was looking for, and while I'd usually dive into the manuals in this instance I don't have the time, or the mental capacity to do so.Thanks again :)
Jon
@Quassnoi: What about `SUM(amount * accessory)`? Works as long as `accessory` is always 0 or 1. Admittedly, it is a little bit sloppy.
Tomalak
@Tomalak - haha thanks. I thought that as I submitted! I'll come back with a real sql question some day.
Jon
@Jon: Sorry if it sounded rude, I didn't mean nothing like that :) I meant that *given a working program*, finding out how it works is of much more use (and fun) than reading the descriptions.
Quassnoi
@Tomalak: will work if accessory is a `BIT`. However, this is sloppy indeed :)
Quassnoi
@Quassnoi: Will work for `INT`, too. Preferably if there is a check constraint in place that limits the value. ;) The key question is - will it be faster?
Tomalak
@Tomalak: with a check constraint will work too of course. It will hardly be faster, though. Also, storing boolean values in `BIT` columns saves space: in `SQL Server`, `8` `BIT` columns still occupy `1` byte of storage space (unlike `8` `INT` columns which would occupy as much as `32` bytes).
Quassnoi