I am trying to write a SQL statement that will create a flattened table from source table data. This is what I am trying to do :
- get the status and sum of its quantity for a combination of orderid, partid
I tried to accomplish this with the following query based on case expression:
SELECT orderid, partid,
SUM(quantity) as total,
status1 = case [status] when 1 then SUM(quantity) else null end,
status2 = case [status] when 2 then SUM(quantity) else null end,
status3 = case [status] when 3 then SUM(quantity) else null end
FROM partsum
GROUP BY orderid,
partid,
status;
But the results are not what I require. I know I am grouping with status but the query will not compile without adding it to the list.

There are a bunch of ways to write this. Also I converted your nulls to zeros, but it could be easy enough to switch them back to nulls if that’s what you really need. You didn’t specify whic version of SQL, so here are two solutions that will work:
A SQL 2005+ Version:
Should work on any version (and by any i mean at least back to SQL 6.5):