过滤行组

时间:2014-06-04 01:10:57

标签: sql sql-server

以下是我得到的数据集 人,格式和不同的角色(位) 我想得到每个 Format 组都选择了所有3个角色的所有行。例如:新格式没有选择编辑角色。所以我想获得不包含 Novel 记录的数据 我怎样才能做到这一点?

enter image description here

3 个答案:

答案 0 :(得分:1)

您的第一个问题是“我希望获得每个格式组都选择了所有3个角色的所有行。”你可以使用窗口函数来解决这个问题:

select name, format, write, director, editor
from (select t.*,
             max(cast(writer as int)) over (partition by format) as maxwriter,
             max(cast(director as int)) over (partition by format) as maxdirector,
             max(cast(editor as int)) over (partition by format) as maxeditor
      from table t
     ) t
where maxwriter = 1 and maxdirector = 1 and maxeditor = 1;

如果你想获得没有编辑器的行,你可以使用类似的方法,只需更改where子句:

where maxwriter = 1 and maxdirector = 1 and maxeditor = 0;

答案 1 :(得分:0)

select format
from your_table
group by format
having sum(case when writer = 1 then 1 else 0 end) > 0
and sum(case when director = 1 then 1 else 0 end) > 0
and sum(case when editor = 1 then 1 else 0 end) > 0

如果您需要完整的行而不是format,那么您可以执行

select * from your_table
where format in 
(
    select format
    from your_table
    group by format
    having sum(case when writer = 1 then 1 else 0 end) > 0
    and sum(case when director = 1 then 1 else 0 end) > 0
    and sum(case when editor = 1 then 1 else 0 end) > 0
)

答案 2 :(得分:0)

这是查询:

select * from (
    select format, count(*) as total_count    
    from table    
    group by format    
) as t1    
inner join (    
    select format, count(*) as total_count
    from table
    where writer=1 and director=1 and editor=1
    group by format
) as t2
on t1.format=t2.format and t1.total_count=t2.total_count

主要思路 - 计算每种格式的行数,然后计算满足条件的行数