SQL SUM多列并基于一列

时间:2017-09-30 23:22:24

标签: sql

我需要帮助添加到我的SQL语句中。所有数据都位于同一个表中。我目前的代码如下,

SELECT Date,
       Val2,
       SNumber,
       SUM(isnull(L1,0) + isnull(L2,0) + isnull(L3,0)) As TotalR,
From Table1
Where Val2='Rep'
Group By 

价值2同时包含"存储"和" Rep"

我有L1,L2和L3的总数很好(对于Rep)。 我需要帮助的是如何获得

总计" Store" L1,L2和L3在哪里 SNumber匹配" Rep"和" Store"

部分"代表"在同一个"商店"并且应该有相同的总数。

Source Table                    
Date    Val2    Snumber L1  L2  L3
x   Store   1   11  5   4
x   Store   2   6   8   10
x   Rep1    1   5   2   1
x   Rep2    1   6   3   3
x   Rep3    2   2   1   5
x   Rep4    2   3   3   3
x   Rep5    2   1   4   2

结果

Date    Val2    Snumber TotalR  TotalS  
x   Rep1    1   8   20  
x   Rep2    1   12  20  
x   Rep3    2   8   24  
x   Rep4    2   9   24  
x   Rep5    2   7   24  

2 个答案:

答案 0 :(得分:1)

您需要将内连接与同一表Table1的子查询一起使用。

下面我准备了用于创建和插入指定示例数据的脚本:

CREATE TABLE Table1 (
    Date DateTime,
    Val2 Varchar(5),
    SNumber Smallint,
    L1 Smallint,
    L2 Smallint,
    L3 Smallint
)

运行此插入脚本以在表上创建数据。

INSERT INTO Table1
VALUES(CAST(GETDATE() AS DATE), 'Store', 1, 11, 5, 4),
(CAST(GETDATE() AS DATE), 'Store', 2, 6, 8, 10),
(CAST(GETDATE() AS DATE), 'Rep1', 1, 5, 2, 1),
(CAST(GETDATE() AS DATE), 'Rep2', 1, 6, 3, 3),
(CAST(GETDATE() AS DATE), 'Rep3', 2, 2, 1, 5),
(CAST(GETDATE() AS DATE), 'Rep4', 2, 3, 3, 3),
(CAST(GETDATE() AS DATE), 'Rep5', 2, 1, 4, 2)

如果您运行以下脚本,则在创建的表上,您将获得预期结果:

SELECT Date, Val2, Table1.SNumber, (L1 + L2 + L3) AS TotalR, S.TotalS
FROM Table1(NOLOCK)
  JOIN (
      SELECT SNumber, L1 + L2 + L3 AS TotalS
      FROM Table1(NOLOCK)
      WHERE Val2 = 'Store'
   ) S
   ON Table1.SNumber = S.SNumber
 WHERE Val2 <> 'Store'

试试SQL Fiddle

<强>此外: 以下脚本列出了具有最大TotalS的商店的回购:

SELECT Date, Val2, Table1.SNumber, (L1 + L2 + L3) AS TotalR, S.TotalS
FROM Table1(NOLOCK)
  JOIN (
      SELECT TOP 1 SNumber, L1 + L2 + L3 AS TotalS
      FROM Table1(NOLOCK)
      WHERE Val2 = 'Store'
      ORDER BY TotalS DESC
   ) S
   ON Table1.SNumber = S.SNumber
 WHERE Val2 <> 'Store'

答案 1 :(得分:0)

SELECT  b.Date,
        b.Val2,
        b.Snumber,
        L1+L2+L3 AS TotalR,
        SUM(L1+L2+L3) OVER (PARTITION BY Snumber)
FROM    (
            SELECT  Val2
            FROM    Table1
            WHERE   Val2 LIKE 'Rep%'
        ) a
        JOIN Table1 b
            ON a.Val2 = b.Val2