SQL连接 - 识别缺失的行

时间:2016-03-20 08:59:07

标签: sql sql-server sql-server-2012

我需要找到具有特定标记的所有行,这些行没有具有不同标记的对应行。

我的表格结构如下:

Year, Week, Brand, Country, LoactionCode, ProductCategory, VolumeType, Division, Activity, Tag, Qty

一些数据样本:

 2016,1,Dell, USA, 100, Computers, Accessories, Retail, Pricing, 'CF',800
 2016,1,Dell, USA, 100, Computers, Accessories, Retail, Tagging, 'CF',1500
 2016,1,Dell, USA, 100, Computers, Accessories, Retail, Pricing, 'OF',1000
 2016,1,Dell, USA, 100, Computers, Accessories, Retail, Tagging, 'OF',1200
 2016,1,Dell, USA, 100, Computers, Accessories, Retail, Bagging, 'OF',1200

我想获取标记为“OF”的行,但没有相应的行,标记“CF”匹配所有字段“Year,Week,Brand,Country,LoactionCode,ProductCategory,VolumeType,Division,活性“

请有人帮我这个吗?

2 个答案:

答案 0 :(得分:2)

您可以使用having子句来执行此操作:

SELECT t.year,t.week,t.brand.....t.tag,sum(t.qty?)
FROM YourTable t
GROUP BY t.year,t.week,t.brand.....
HAVING count(CASE WHEN t.tag = 'OF' then 1 end) > 0
   AND count(CASE WHEN t.tag = 'CF' then 1 end) = 0

我不知道你想用qty字段做什么,当有超过1行且tag ='OF'时,你可以将它从总和改为最大或任何要求。

答案 1 :(得分:1)

我已将您的样本数据更改为适合测试目的的内容:

  • 有3行Tag = OF
  • 一个匹配的CF行
  • 一个不匹配的
  • 因此,期望最终结果集中有2行

查询使用CTE生成样本数据 该解决方案使用常规查询来选择您可能感兴趣的OF行,并使用EXCEPT后跟定义您希望从先前结果​​集中排除的行的查询。

;with SampleData AS (
    SELECT  2016 as Year, 1 AS Week, 'Dell' AS Brand, 'CF' AS Tag, 800 AS Qty
    UNION ALL SELECT 2016, 1, 'AMD', 'CF', 1500
    UNION ALL SELECT 2016, 1, 'Intel', 'OF', 1000
    UNION ALL SELECT 2016, 1, 'Apple', 'OF', 1200
    UNION ALL SELECT 2016, 1, 'Dell', 'OF', 1200
)
--Solution uses CTE from above
SELECT  Year, Week, Brand
FROM    SampleData
WHERE   Tag = 'OF'
EXCEPT
SELECT  Year, Week, Brand
FROM    SampleData
WHERE   Tag = 'CF'