仅汇总具有给定标准的行

时间:2016-12-16 11:20:48

标签: tsql

一切! 给出以下表结构

DECLARE @TempTable TABLE
(
    idProduct INT, 
    Layers INT, 
    LayersOnPallet INT, 
    id INT IDENTITY(1, 1) NOT NULL, 
    Summarized BIT NOT NULL DEFAULT(0)
)

以及以下生成测试数据的插入语句

INSERT INTO @TempTable(idProduct, Layers, LayersOnPallet)
SELECT 1, 2, 4
UNION ALL
SELECT 1, 2, 4
UNION ALL
SELECT 1, 1, 4
UNION ALL
SELECT 2, 2, 4

我只想总结那些具有相同idProduct的行(仅限图层),并且这些行的总和等于LayersOnPallet。

一张图片胜过千言万语:

enter image description here

从上图中,您可以看到只汇总了第一行,因为两者都具有相同的idProduct,而sum(layers)将等于LayersOnPallet。 我怎样才能做到这一点?有没有办法只在选择中做这个(不是用while)?

谢谢!

1 个答案:

答案 0 :(得分:1)

也许这会成功。请注意我的评论:

-- your sample data
DECLARE @TempTable TABLE
(
    idProduct INT, 
    Layers INT, 
    LayersOnPallet INT, 
    id INT IDENTITY(1, 1) NOT NULL, 
    Summarized BIT NOT NULL DEFAULT(0)
)
INSERT INTO @TempTable(idProduct, Layers, LayersOnPallet)
SELECT 1, 2, 4 UNION ALL
SELECT 1, 2, 4 UNION ALL
SELECT 1, 1, 4 UNION ALL
SELECT 2, 2, 4;

-- an intermediate temp table used for processing
IF OBJECT_ID('tempdb..#processing') IS NOT NULL DROP TABLE #processing;

-- let's populate the #processing table with duplicates
SELECT 
  idProduct, 
  Layers,
  LayersOnPallet,
  rCount = COUNT(*)
INTO #processing
FROM @tempTable
GROUP BY 
  idProduct, 
  Layers,
  LayersOnPallet
HAVING COUNT(*) > 1;

-- Remove the duplicates 
DELETE t 
FROM @TempTable t
JOIN  #processing p
  ON  p.idProduct      = t.idProduct 
  AND p.Layers         = t.Layers
  AND p.LayersOnPallet = t.LayersOnPallet

-- Add the new, updated record
INSERT @TempTable
SELECT  
  idProduct, 
  Layers * rCount,
  LayersOnPallet, 1
FROM #processing;

DROP TABLE #processing; -- cleanup

-- Final output
SELECT idProduct, Layers, LayersOnPallet, Summarized
FROM @TempTable;

结果:

idProduct   Layers      LayersOnPallet Summarized
----------- ----------- -------------- ----------
1           4           4              1
1           1           4              0
2           2           4              0