33

我有一个具有以下架构的表 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

4 回答 4

95

尝试

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

于 2013-05-13T08:04:13.623 回答
6

试试这个查询

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 小提琴

| ORDERID | CNT | TOTALCOPYCOST | TOTALFULLPRICE |
--------------------------------------------------
|      16 |   4 |           150 |            100 |
于 2013-05-13T08:04:29.293 回答
4

你能用:

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
于 2013-05-13T08:04:09.557 回答
1

你也可以试试...

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

于 2013-05-13T08:16:03.967 回答