0

我有一个这样的 SQL 表。

OrderID  ItemID  ItemPrice   ItemType
1        A       100         1
1        B       50          1
1        C       10          0
2        A       100         1
2        F       60          0
3        G       10          0

所以我想像这样出去?

OrderID ItemPrice -Type= 1  ItemPrice -Type= 0
1             150                     10
2             10                      60
3             10    

您对要使用的 SQL 命令有任何想法吗?我认为它是按订单 ID 和项目类型分组的。

4

4 回答 4

0

尝试这个::

Select 
DISTINCT(orderId),
(Select   SUM(ITEMPRICE) from table where Itemtype=1 group by ORDERID) as ItemType1, 
(Select   SUM(ITEMPRICE) from table where Itemtype=0 group by ORDERID) as ItemType0

from table
于 2012-12-05T04:36:52.757 回答
0

未经测试,但这应该适合你。

SELECT t1.OrderID, 
ItemPrice-Type1 = SUM(t1.ItemPrice), 
ItemPrice-Type2 = SUM(t2.ItemPrice)
FROM TableName t1
INNER JOIN TableName t2 on t1.OrderID = t2.OrderID and t1.ItemID = t2.ItemID
WHERE t1.ItemType = 1 AND t2.ItemType = 0
GROUP BY t1.OrderID
于 2012-12-05T04:40:08.707 回答
0

您正在做的是枢轴转换。有几种方法可以做到这一点,但我最喜欢的方法是在 SUM 中使用 CASE:

SELECT
    OrderId,
    SUM(CASE WHEN ItemType = 0 THEN ItemPrice ELSE 0 END) AS Type0_Price,
    SUM(CASE WHEN ItemType = 1 THEN ItemPrice ELSE 0 END) AS Type1_Price
FROM MyTable
GROUP BY OrderId

如果您有两种以上的类型,则可以很好地扩展。您所要做的就是SUM(...)在选择列表中添加另一行,而无需更改查询的其余部分。

认为这会很好地执行,因为 SELECT 列表中的计算可以在不产生额外的行扫描或查找的情况下完成。这是自联接和子选择的缺点。

于 2012-12-05T04:40:17.993 回答
0

这有效吗?:

SELECT
    OrderID, 
    SUM(ItemPrice*ItemType) Type1,
    SUM(ItemPrice*(1-ItemType)) Type0 
FROM 
    TableName 
GROUP BY OrderID
于 2012-12-05T04:48:27.923 回答