使用3列将2行合并为1行

时间:2013-08-02 14:02:47

标签: sql-server

我正在尝试将以下结构放入一行:

ID     SubID    Total1  Total2  Total3
-----  -------  ------  ------  ------
Apple  Fruit    12      null    12
Apple  Veggies  null    24      24

这是我想要的结果:

ID     FruitTotal  VeggieTotal  TotalTotal
-----  ----------  -----------  ----------  
Apple  12          24           36

5 个答案:

答案 0 :(得分:4)

DECLARE @Id AS VARCHAR(50)
SET @Id = 'Apple'

IF @Id IS NULL
BEGIN
    SELECT ID,
           SUM(ISNULL(Total1,0)) AS Total1,
           SUM(ISNULL(Total2,0)) AS Total2,
           SUM(ISNULL(Total3,0)) AS Total3
    FROM   Table
    GROUP BY ID
END
ELSE
    SELECT ID,
           SUM(ISNULL(Total1,0)) AS Total1,
           SUM(ISNULL(Total2,0)) AS Total2,
           SUM(ISNULL(Total3,0)) AS Total3
    FROM   Table
    WHERE  ID = @Id
    GROUP BY ID
BEGIN
END

修改

你可能需要这个

DECLARE @Id AS VARCHAR(50)
SET @Id = 'Apple'

IF @Id IS NULL
BEGIN
    SELECT ID,
           (SELECT SUM(Total1) FROM Table WHERE ID = T.ID AND SubId = 'Fruit') AS FruitTotal,
           (SELECT SUM(Total2) FROM Table WHERE ID = T.ID AND SubId = 'Veggies') AS VeggiesTotal
           SUM(ISNULL(Total3,0)) AS Total3
    FROM   Table T
    GROUP BY ID
END
ELSE
    SELECT ID,
           (SELECT SUM(Total1) FROM Table WHERE ID = T.ID AND SubId = 'Fruit') AS FruitTotal,
           (SELECT SUM(Total2) FROM Table WHERE ID = T.ID AND SubId = 'Veggies') AS VeggiesTotal
           SUM(ISNULL(Total3,0)) AS Total3
    FROM   Table T
    WHERE  ID = @Id
    GROUP BY ID
BEGIN
END

答案 1 :(得分:1)

除非我遗漏了什么,否则你需要三个SUM s:

SELECT ID, SUM(Total1), SUM(Total2), SUM(Total3)
FROM myTable
GROUP BY ID

SQL Fiddle example

答案 2 :(得分:0)

SELECT   ID,
         SUM(Total1),
         SUM(Total2),
         SUM(Total3)
FROM     FruitTable
GROUP BY ID;

查看SQL中的Aggregate FunctionsSUM function

答案 3 :(得分:0)

select id, 
    sum(coalesce(total1,0)) as Total1, 
  sum(coalesce(total2,0)) as Total2, 
  sum(coalesce(total3,0))  as Total3
from t
group by id

答案 4 :(得分:0)

它与您已经看到的相似 - 但是在单行中没有用于对进行求和的聚合。所以你只需要手动完成数学运算:

select
    ID,
    SUM(COALESCE(Total1,0)) as FruitTotal,
    SUM(COALESCE(Total2,0)) as VeggieTotal,
    SUM(COALESCE(Total1,0) + COALESCE(Total2,0)) as TotalTotal
from
    [Table]
group by ID