从源表数据创建Flatnedned记录

时间:2012-02-27 14:04:24

标签: sql-server

我正在尝试编写一个SQL语句,它将从源表数据创建一个展平的表。这就是我想要做的事情:

  • 获取orderid,partid
  • 组合的状态和数量总和

我尝试使用以下基于案例表达式的查询来完成此操作:

SELECT orderid, partid, 
       SUM(quantity) as total,
       status1 =  case [status] when 1 then SUM(quantity) else null end,
       status2 =  case [status] when 2 then SUM(quantity) else null end,
       status3 =  case [status] when 3 then SUM(quantity) else null end 
FROM   partsum
GROUP BY  orderid,
          partid,
          status;

但结果不是我要求的。我知道我正在使用状态进行分组,但如果不将其添加到列表中,查询将无法编译。

enter image description here

2 个答案:

答案 0 :(得分:1)

有很多方法可以写这个。此外,我将您的空值转换为零,但如果这是您真正需要的,它可以很容易地将它们切换回空值。您没有指定SQL的哪个版本,因此这里有两个解决方案:

SQL 2005+版本:

SELECT  DISTINCT 
        OrderID, 
        PartID,
        SUM(Quantity) OVER (PARTITION BY PartID) as Total,
        SUM( case [status] when 1 then quantity else 0 end) 
                OVER (Partition By PartID) as Status1,
        SUM( case [status] when 2 then quantity else 0 end) 
                OVER (Partition By PartID) as Status2,
        SUM( case [status] when 3 then quantity else 0 end) 
                OVER (Partition By PartID)as Status3
FROM    PartSum

应该可以在任何版本上工作(并且我的意思是至少回到SQL 6.5):

SELECT  
        OrderID, 
        PartID,
        SUM(Quantity) as Total,
        SUM( case [status] when 1 then quantity else 0 end) as Status1,
        SUM( case [status] when 2 then quantity else 0 end) as Status2,
        SUM( case [status] when 3 then quantity else 0 end) as Status3
FROM    PartSum
GROUP BY  orderid,
          partid

答案 1 :(得分:1)

尝试这样的事情:

SELECT DISTINCT [Order].OrderID,
    [Order].PartID,
    [Order].Total,
    Status1.Status AS Status1,
    Status2.Status AS Status2,
    Status3.Status AS Status3
FROM 
    (SELECT OrderID, PartID, SUM(Quantity) AS Total
        FROM PartSum
        GROUP BY OrderID, PartID) [Order]
    LEFT JOIN PartSum Status1 ON [Order].OrderID = Status1.OrderID AND [Order].PartID = Status1.PartID AND Status1.Status = 1
    LEFT JOIN PartSum Status2 ON [Order].OrderID = Status2.OrderID AND [Order].PartID = Status2.PartID AND Status2.Status = 2
    LEFT JOIN PartSum Status3 ON [Order].OrderID = Status3.OrderID AND [Order].PartID = Status2.PartID AND Status3.Status = 3

假设您有可用状态代码的固定数量。