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

1              2              NULL
2              2              NULL
3              2              NULL

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

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

4

2 回答 2

2
  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;

Sample Data

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);

Result:

division    department  depthead
----------- ----------- ------------
2           1           Mr Head
1           2           NULL
于 2013-05-20T22:53:01.467 回答
2
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

Example at SQL Fiddle.

于 2013-05-20T22:55:12.370 回答