簡體   English   中英

Group By條件求和MSSQL查詢

[英]Conditional sum in Group By query MSSQL

我有一個表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值。

任何幫助將非常感激。

關心弗雷迪

嘗試

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

試試這個查詢

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 |

你能用:

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

你也可以試試......

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM