繁体   English   中英

SQL选择,从列条件中选择一行

[英]SQL Select, selecting a row off of a column condition

Division    Department  Dept. Head
1              1             Mr. Anon     
2              1              NULL 
3              1              NULL 

1              2              NULL
2              2              NULL
3              2              NULL

我正在尝试编写一个查询,该查询将根据第三列(部门负责人)的条件选择行。 如果部门主管中有一行不为空(Anon先生),请选择该行。 如果部门主管中没有没有非零值的行,请选择任何行。

因此,在上表中的两个组中,我只想从每个组中选择一行。

  select division, department, depthead
    from tbl
   where depthead is not null
   union all
  select min(division) any_division, department, NULL
    from tbl
group by department
  having count(depthead) = 0;

样本数据

create table tbl (
    division int, department int, depthead varchar(100),
    primary key(department, division));
insert into tbl values (1, 1, null);
insert into tbl values (2, 1, 'Mr Head');
insert into tbl values (3, 1, null);
insert into tbl values (1, 2, null);
insert into tbl values (2, 2, null);
insert into tbl values (3, 2, null);

结果:

division    department  depthead
----------- ----------- ------------
2           1           Mr Head
1           2           NULL
select  *
from    (
        select  row_number() over (
                    partition by department
                    order by case when depthead is not null then 1 else 2 end
                    ) as rn
        ,       yt.*
        from    YourTable yt
        ) SubQueryAlias
where   rn = 1

SQL Fiddle中的示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM