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

1              2              NULL
2              2              NULL
3              2              NULL

3列目(部長)の条件で行を選択するクエリを書こうとしています。部門長に null でない行がある場合 (Mr. Anon)、その行を選択します。部門長に NULL 以外の値を持つ行がない場合は、任意の行を選択します。

したがって、上の表にある 2 つのグループから、それぞれから 1 つの行だけを選択したいと考えています。

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;

サンプルデータ

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
于 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

SQL Fiddle の例。

于 2013-05-20T22:55:12.370 に答える