如果表2中存在行,则为2列的总和 - SQL

时间:2017-01-10 15:36:09

标签: sql

CREATE TABLE #Details
(
SName       VARCHAR(20),
PName       VARCHAR(20),
SoldCount   INT,
Value       INT
)

CREATE TABLE #DetailsException
(
ExSName     VARCHAR(20),
ExPName     VARCHAR(20)
)

INSERT INTO #Details(SName, PName, SoldCount,Value) VALUES ('Store 1', 'Product 1', 10,400)
INSERT INTO #Details(SName, PName, SoldCount,Value) VALUES ('Store 1', 'Product 3', 3,500)
INSERT INTO #Details(SName, PName, SoldCount,Value) VALUES ('Store 2', 'Product 1', 8,30)
INSERT INTO #Details(SName, PName, SoldCount,Value) VALUES ('Store 2', 'Product 2', 10,25)
INSERT INTO #Details(SName, PName, SoldCount,Value) VALUES ('Store 2', 'Product 2', 23,120)
INSERT INTO #Details(SName, PName, SoldCount,Value) VALUES ('Store 4', 'Product 1', 23,50)
INSERT INTO #Details(SName, PName, SoldCount,Value) VALUES ('Store 4', 'Product 3', 10,50)
INSERT INTO #Details(SName, PName, SoldCount,Value) VALUES ('Store 4', 'Product 5', 7,200)
INSERT INTO #Details(SName, PName, SoldCount,Value) VALUES ('Store 5', 'Product 1', 10,100)
INSERT INTO #Details(SName, PName, SoldCount,Value) VALUES ('Store 5', 'Product 1', 24,240)

INSERT INTO #DetailsException(ExSName, ExPName) VALUES ('Store 2', 'Product 2')
INSERT INTO #DetailsException(ExSName, ExPName) VALUES ('Store 4', 'Product 5')

SELECT SName, PName, **CASE WHEN EXISTS(SELECT 1 FROM #DetailsException WHERE ExSName = SName AND ExPName = PNAme ) THEN 0 ELSE SUM(SoldCount) END AS SoldCount**, SUM(Value) AS Value
FROM #Details
GROUP BY SNAME, PNAME
ORDER BY SNAME, PNAME

结果集正确无误。虽然我想知道是否有任何其他优化的方式在SQL中编写它。由于这两个表的大小都会变得非常大。

感谢。

2 个答案:

答案 0 :(得分:0)

我想我更倾向于将其写为LEFT JOIN

SELECT d.SName, d.PName, 
       SUM(CASE WHEN de.ExSname IS NOT NULL THEN 0 ELSE SoldCount END) AS SoldCount,
       SUM(Value) AS Value
FROM #Details d LEFT JOIN
     #DetailsException de
     ON de.ExSName = d.SName AND de.ExPName = d.PNAme
GROUP BY d.SNAME, d.PNAME
ORDER BY d.SNAME, d.PNAME;

但是,你的方法很好。

答案 1 :(得分:0)

考虑到ExSName, ExPName

中是唯一的

以下是使用LEFT JOIN的另一种方式。

SELECT SName,
       PName,
       Sum(CASE
             WHEN de.ExSName IS NULL THEN ( SoldCount )
             ELSE 0
           END)   AS SoldCount,
       Sum(Value) AS Value
FROM   #Details d
       LEFT JOIN (select distinct ExSName,ExPName from #DetailsException) de
              ON de.ExSName = d.SName
                 AND de.ExPName = d.PNAme
GROUP  BY SNAME,
          PNAME
ORDER  BY SNAME,
          PNAME 

通过运行查询来检查性能。您可以在SName,PNAme列上创建非聚集索引以提高性能

CREATE NONCLUSTERED INDEX IX_details_temp
  ON #Details (SNAME, PNAME)
  include (SoldCount, Value); 

添加覆盖索引(SoldCount, Value)以避免群集/堆查找。注意,仅当您要从#details表中过滤记录时,索引才有用。对于#DetailsException表,创建以下索引可能会有所帮助

 CREATE NONCLUSTERED INDEX IX_DetailsException_temp
  ON #DetailsException (ExSName, ExPName)