将多行的值加到新列中

时间:2019-04-15 15:53:13

标签: sql sql-server stored-procedures

我有一个存储过程,返回的表如下:

ID | Type | Price | Description
-------------------------------
2  | J    | 40.00 | Job
2  | F    | 10.00 | Freight
2  | P    | 20.00 | Postage
2  | F    |  5.00 | Handling
7  | J    | 50.00 | Job
7  | F    | 20.00 | Freight
7  | P    | 30.00 | Postage
7  | H    |  5.00 | Handling

我希望它返回这样的表:

ID | Type | Price | Description | FreightPrice
-----------------------------------------
2  | J    | 40.00 | Job         | 15.00
2  | F    | 10.00 | Freight     | 15.00    
2  | P    | 20.00 | Postage     | 15.00
2  | F    |  5.00 | Freight     | 15.00
7  | J    | 50.00 | Job         | 20.00
7  | F    | 20.00 | Freight     | 20.00
7  | P    | 30.00 | Postage     | 20.00
7  | H    |  5.00 | Handling    | 20.00

预期结果将每个唯一ID的总运费汇总到其自己的列中,即ID#2的FreightPrice总价为15.00美元。

我尝试使用以下方法获得该结果

FreightPrice = (SELECT SUM(Price) 
                FROM Table
                WHERE Type = 'F' AND ID >= 2 AND ID <= 7)

此问题是,它返回“运价”为$ 35.00,因为它将所有类型为“ F”的实例加起来。

我是否需要将它们分为两个不同的子查询,或者有人知道用一个子查询来实现此目的的方法吗?

2 个答案:

答案 0 :(得分:4)

您似乎想要一个窗口功能:

select t.*,
       sum(case when description = 'freight' then price end) over (partition by id) as freightprice
from t;

答案 1 :(得分:2)

窗口函数是更好的方法,但是您也可以尝试以下方法:

输入:

CREATE TABLE #Data (
   ID int,
   [Type] varchar(1),
   Price numeric(10, 2),
   Description varchar(50)
)
INSERT INTO #Data
   (ID, [Type], Price, Description)
VALUES   
   (2, 'J', 40.00, 'Job'),
   (2, 'F', 10.00, 'Freight'),
   (2, 'P', 20.00, 'Postage'),
   (2, 'F',  5.00, 'Handling'),
   (7, 'J', 50.00, 'Job'),
   (7, 'F', 20.00, 'Freight'),
   (7, 'P', 30.00, 'Postage'),
   (7, 'H',  5.00, 'Handling')

声明:

SELECT t.*, s.*
FROM #Data t
LEFT JOIN (
   SELECT ID, SUM(Price) AS FreightPrice 
   FROM #Data 
   WHERE [Type] = 'F' 
   GROUP BY [ID]
) s ON (t.ID = s.ID)

输出:

ID  Type    Price   Description ID  FreightPrice
2   J       40.00   Job         2   15.00
2   F       10.00   Freight     2   15.00
2   P       20.00   Postage     2   15.00
2   F       5.00    Handling    2   15.00
7   J       50.00   Job         7   20.00
7   F       20.00   Freight     7   20.00
7   P       30.00   Postage     7   20.00
7   H       5.00    Handling    7   20.00