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

时间:2013-05-20 22:49:18

标签: sql sql-server tsql sql-server-2005

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

1              2              NULL
2              2              NULL
3              2              NULL

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

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

2 个答案:

答案 0 :(得分: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;

样本数据

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

答案 1 :(得分: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.