TSQL查找重复记录的缺失值

时间:2015-04-22 19:44:55

标签: sql sql-server database sql-server-2008

示例数据:

PageID  Attribute
2860    Category
2860    Sub-Category
2861    Tag
2861    Tag
2862    Tag
2862    Category
2863    Sub-Category
2883    Category
2883    Sub-Category

问题#1:我需要查找属性Sub-Category不存在的页面ID,因此我的结果应为:

2861
2862

问题#2:我需要找到属性Sub-Category和属性Category都不存在的页面ID,因此我的结果应为:

2861

3 个答案:

答案 0 :(得分:1)

1)

select pageid 
from thetable 
where pageid not in (select pageid from thetable where attribute = 'sub-category')

2)

select pageid 
from thetable 
where pageid not in (select pageid from thetable where attribute = 'sub-category')
and pageid not in (select pageid from thetable where attribute = 'category')

答案 1 :(得分:1)

SQL-as-plain-English解决方案:

问题#1 :我需要找到属性Sub-Category不存在的页面ID。换句话说,“所有页面ID除了属于'子类别'的

SELECT PageID FROM MyTable
EXCEPT
SELECT PageID FROM MyTable WHERE Attribute = 'Sub-Category'

问题#2 :我需要找到属性Sub-Category和属性Category都不存在的页面ID。换句话说,“除了具有'子类别'或'类别'属性的页面ID之外的所有页面ID

SELECT PageID FROM MyTable
EXCEPT
SELECT PageID FROM MyTable WHERE Attribute IN ('Category','Sub-Category')

答案 2 :(得分:0)

问题1

Select PageID From Table
Group By PageID
Having Sum(Case When Attribute = 'Sub-category' Then 1 Else 0 End) = 0

问题2

Select PageID From Table
Group By PageID
Having Sum(Case When Attribute In('Category', 'Sub-category') Then 1 Else 0 End) = 0