Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

sql - Conditional sum in Group By query MSSQL

I have a table OrderDetails with the following schema:

----------------------------------------------------------------
|  OrderId  |  CopyCost  |  FullPrice  |  Price  |  PriceType  |
----------------------------------------------------------------
|  16       |  50        |  100        |  50     |  CopyCost   |
----------------------------------------------------------------
|  16       |  50        |  100        |  100    |  FullPrice  |
----------------------------------------------------------------
|  16       |  50        |  100        |  50     |  CopyCost   |
----------------------------------------------------------------
|  16       |  50        |  100        |  50     |  CopyCost   |
----------------------------------------------------------------

I need a query that will surmise the above table into a new table with the following schema:

----------------------------------------------------------------
|  OrderId  |  ItemCount  |  TotalCopyCost  |  TotalFullPrice  |
----------------------------------------------------------------
|  16       |  4          |  150            |  100             |
----------------------------------------------------------------

Currently I am using a Group By on the Order.Id to the the item count. But I do not know how to conditionally surmise the CopyCost and FullPrice values.

Any help would be much appreciated.

Regards Freddie

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try

SELECT OrderId, 
       COUNT(*) ItemCount,
       SUM(CASE WHEN PriceType = 'CopyCost' THEN Price ELSE 0 END) TotalCopyCost,
       SUM(CASE WHEN PriceType = 'FullPrice' THEN Price ELSE 0 END) TotalFullPrice
  FROM OrderDetails
 GROUP BY OrderId

SQLFiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...