tags:

views:

43

answers:

3

I would like to get the following data (and more) into a single view.

SELECT Price FROM dbo.OrderItems WHERE OrderItemTypeId = 0 

And

SELECT SUM (Price) AS ShippingTotal FROM dbo.OrderItems WHERE OrderItemTypeId = 1

I can’t seem to figure out how to do this with my weak SQL skills. Anybody know how I could do this?

+3  A: 

You can use UNION statement:

SELECT Price FROM dbo.OrderItems WHERE OrderItemTypeId = 0 

UNION

SELECT SUM (Price) AS ShippingTotal FROM dbo.OrderItems WHERE OrderItemTypeId = 1

But what is the semantic behind this ... In the first statement you have only one row with id = 0, in the second an aggregate function grouped by the same column (which suppose that there are more than one record with id=1). It will be helpful to show us the sample data for you table.

To improve your skills about UNION, see here: http://www.w3schools.com/sql/sql_union.asp

anthares
1) I would add another column to the result-set so that one knows which one is total (the column caption will be the same)2) if no other column is added to the result view, you should really use UNION ALL. Otherwise if 2 results are equal, one row will be removed as a duplicate.
van
As I can't really get the idea of this query, I'm not sure that there should be duplicate rows ... That's why I skipped the ALL option... You're right in general, it could be useful, too.
anthares
Yes, more data would have been in order, so much for trying to keep it simple. What I really needed was just a simple subquery that did the SUM calculation for me. Just couldn't get my mind around it. I'll give you the check as yours was the most productive answer
Jim
+1  A: 

To cover all OrderItemTypeId...

SELECT OrderItemTypeId, SUM(Price) AS ShippingTotal
FROM dbo.OrderItems 
GROUP BY OrderItemTypeId 
kevchadders
A: 

One way would be like this:

SELECT Price, 0 AS OrderItemTypeId FROM dbo.OrderItems WHERE OrderItemTypeId = 0 
UNION ALL
SELECT SUM(Price) AS Price, 1 AS OrderItemTypeId FROM dbo.OrderItems 
WHERE OrderItemTypeId = 1

The 2nd column I've added to the results allows you to determine the different rows.

AdaTheDev