Group By条件求和MSSQL查询

时间:2013-05-13 08:00:22

标签: sql

我有一个包含以下模式的表OrderDetails:

----------------------------------------------------------------
|  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   |
----------------------------------------------------------------

我需要一个查询,将上表推测为具有以下模式的新表:

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

目前我在Order.Id上使用Group By来计算项目数。但我不知道如何有条理地推测CopyCost和FullPrice值。

非常感谢任何帮助。

此致 房地

4 个答案:

答案 0 :(得分:63)

尝试

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

答案 1 :(得分:4)

尝试此查询

select 
   orderId, 
   count(*) as cnt, 
   sum(if(pricetype='CopyCost', CopyCost, 0)) as totalCopyCost,
   sum(if(pricetype='FullPrice', FullPrice, 0)) as totalFullPrice
from 
   tbl
group by 
   orderId

SQL FIDDLE

| ORDERID | CNT | TOTALCOPYCOST | TOTALFULLPRICE |
--------------------------------------------------
|      16 |   4 |           150 |            100 |

答案 2 :(得分:3)

你可以使用:

SELECT
  OrderId,
  Count(1) as ItemCount,
  SUM(CASE WHEN PriceType = 'CopyCost' 
        THEN CopyCost ELSE 0 END) AS TotalCopyCost,
  SUM(CASE WHEN PriceType = 'FullPrice' 
        THEN FullPrice ELSE 0 END) AS TotalFullPrice
FROM OrderDetails
GROUP BY OrderId

答案 3 :(得分:0)

你也可以试试......

select A.OrderID, A.ItemCount,B.TotalCopyCost, C.TotalFullPrice
from (select OrderID, count(*) as ItemCount from orderdetails) as A,
(select OrderID, sum(CopyCost) as TotalCopyCost from orderdetails where PriceType = 'CopyCost') as B,
(select OrderID, sum(FullPrice) as TotalFullPrice from orderdetails where PriceType = 'FullPrice') as C
where A.OrderID = B.OrderID

SQLFiddle:http://sqlfiddle.com/#!2/946af/6