SQL按日期和ID进行组合

时间:2016-04-21 06:28:09

标签: sql

假设您有结果集,例如:

DATE          ID    cost    
---------------------------------------
 01/01/2011    1     10      
 01/01/2011    1     10      
 01/01/2011    2     10      
 01/01/2011    2     10      

我想要一种方法来对成本值进行求和,但对于每个不同的ID只需要一次,这样当我按日期分组时,我会得到一个结果,例如

DATE                ID1cost   ID2cost
01/01/2011         20             20

2 个答案:

答案 0 :(得分:1)

使用条件聚合:

SELECT
    "Date",
    SUM(CASE WHEN ID = 1 THEN cost ELSE 0 END) AS "ID1Cost",
    SUM(CASE WHEN ID = 2 THEN cost ELSE 0 END) AS "ID2Cost"
FROM tbl
GROUP BY "Date"

答案 1 :(得分:0)

SQL Server PIVOT。希望你不要动态PIVOT。

SELECT Date, [1] AS ID1cost, [2] AS ID2Cost
FROM 
(
    SELECT *
    FROM (VALUES ('01/01/2011', 1, 10), ('01/01/2011', 1, 10), ('01/01/2011', 2, 10), ('01/01/2011', 2, 10)) AS T(Date ,ID, Cost)
) AS T
PIVOT
(
    SUM(Cost)
    FOR ID IN ([1], [2])
) AS P