只选择完整集

时间:2014-03-03 04:32:16

标签: sql sql-server-2008

我想只选择那些每种类型至少有一行的值。

File|Value          |Type  
001 |"Crektolap"    |1  
001 |"123.45"       |2  
001 |"0.00"         |4  
002 |"Cream floure" |1  
002 |"56.89"        |2  
002 |"Supercat"     |3  
002 |"0.01"         |4  

1,2,3,4种类型

我想要的结果是:

File|Value          |Type  
002 |"Cream floure" |1  
002 |"56.89"        |2  
002 |"Supercat"     |3  
002 |"0.01"         |4 

这在一个查询中是否可行?

1 个答案:

答案 0 :(得分:2)

您可以使用窗口函数执行此操作:

select file, value, type
from (select t.*, max(dr) over (partition by file) as numtypes
      from (select t.*, dense_rank() over (partition by file order by type) as dr
            from table t
           ) t
     ) t
where numtypes = 4;

dense_rank()计算每行枚举的type的不同值的数量。然后max()获取最大值,外部查询选择有四种类型的行。

如果您不知道类型的数量:

select file, value, type
from (select t.*, max(dr) over (partition by file) as numtypes
      from (select t.*, dense_rank() over (partition by file order by type) as dr
            from table t
           ) t
     ) t
where numtypes = (select count(distinct type) from table t);