联合重复输入

时间:2014-05-26 09:40:19

标签: sql sql-server

我有三张桌子:

1. Flat Discount
2. Promotion
3. weeklyorder

当我加入这些表并采取联合时,我得到了2行相同数据但有一个不同..如何合并它只显示一行。

查询:

 SELECT skuMaster.SKU,
        (skuMaster.MinimumStock - COUNT(*)) as ReorderQuantity,
        'LowInventory' as descp
   FROM SKUMaster skuMaster
        JOIN InventoryMaster inventoryMaster ON skuMaster.SKU = inventoryMaster.SKU
  GROUP BY skuMaster.sku, skuMaster.MinimumStock, skuMaster.Name
 HAVING COUNT(*) < skuMaster.MinimumStock

  UNION

 SELECT WeeklyOrderList.SKU,
        WeeklyOrderList.Quantity as ReorderQuantity,
        'NoPO' as descp
   FROM WeeklyOrderList
  WHERE WeeklyOrderList.POCGen = 'true'

结果:

SKU ReorderQuantity descp
1   1           LowInventory
2   2           LowInventory
2   2           NoPO
6   5           LowInventory

这里第二和第三是alomost相同的唯一描述是不同的。

我们可以将它们组合在一起,只显示一行descp为lowinventory和NOPO

SKU ReorderQuantity descp
1   1           LowInventory
2   2           LowInventory NoPo
6   5           LowInventory

与上述相同,假设我们有下表

SKU ReorderQuantity     1 1
    2 5
    2 10
    6 5

此处输出应为相同sku的最大重新订购数量

结果:

SKU ReorderQuantity     1 1
    2 10
    6 5

2 个答案:

答案 0 :(得分:2)

;WITH CTE AS 
(
 SELECT skuMaster.SKU,
        (skuMaster.MinimumStock - COUNT(*)) as ReorderQuantity,
        'LowInventory' as descp
   FROM SKUMaster skuMaster
        JOIN InventoryMaster inventoryMaster ON skuMaster.SKU = inventoryMaster.SKU 
  GROUP BY skuMaster.sku, skuMaster.MinimumStock, skuMaster.Name
 HAVING COUNT(*) < skuMaster.MinimumStock

  UNION

 SELECT WeeklyOrderList.SKU,
        WeeklyOrderList.Quantity as ReorderQuantity,
        'NoPO' as descp
   FROM WeeklyOrderList 
  WHERE WeeklyOrderList.POCGen = 'true'
)

SELECT DISTINCT
       a.SKU,
       a.ReorderQuantity,
       descp = STUFF((SELECT ', ' + b.descp
                        FROM CTE b 
                       WHERE b.ReorderQuantity = a.ReorderQuantity 
                         FOR XML PATH('')), 1, 2, '')
  FROM CTE a

答案 1 :(得分:0)

上面提到的输出

的一个例子
DECLARE @t TABLE
(
    SKU INT,
    ReorderQuantity INT
)

 INSERT INTO @t (SKU,ReorderQuantity)
 VALUES (1,1), (2,5), (2,10), (6,5)

 SELECT t.SKU,tt.Qty
   FROM @t t
        INNER JOIN (SELECT MAX(ReorderQuantity)as Qty, SKU
                      FROM @t
                     GROUP BY SKU) tt
              ON tt.SKU = t.SKU
  GROUP BY t.SKU,tt.Qty