有条件地保持行选择

时间:2014-04-09 07:52:00

标签: sql oracle11g

我需要SQL查询的帮助。下表是几个连接表的结果,并按某些列进行过滤。它现在处于(希望是正确的)简化状态。

----------------------
|  A |  B  | C |  D  |
|----+-----+---+-----|
| 81 | 651 | n | 656 |
|----+-----+---+-----|
| 81 | 651 | j | 658 |
|----+-----+---+-----|
| 81 | 804 | n | 659 |
|----+-----+---+-----|
| 81 | 651 | n | 660 |
|----+-----+---+-----|
| 81 | 512 | j | 660 |
|----+-----+---+-----|
| 81 | 670 | j | 660 |
|----+-----+---+-----|
| 81 | 512 | n | 668 |
|----+-----+---+-----|
| 81 | 651 | n | 668 |
|----+-----+---+-----|
| 81 | 670 | n | 668 |
|----+-----+---+-----|
| 81 | 651 | n | 414 |
----------------------

我现在需要进一步定义结果。

  • D
  • 中每个值只有一行
  • 如果有C='j'其中一个。

新结果应如下所示:

----------------------
|  A |  B  | C |  D  |
|----+-----+---+-----|
| 81 | 651 | n | 656 |
|----+-----+---+-----|
| 81 | 651 | j | 658 |
|----+-----+---+-----|
| 81 | 804 | n | 659 |
|----+-----+---+-----|
| 81 | 512 | j | 660 |
|----+-----+---+-----|
| 81 | 512 | n | 668 |
|----+-----+---+-----|
| 81 | 651 | n | 414 |
----------------------

D='660'可以看出,有两行C='j'。我拿了第一个。

对于D='668'C='j'没有行。所以我不在乎应该留哪一个。我拿了第一个。

那我怎么能实现这个目标呢?

3 个答案:

答案 0 :(得分:1)

试试这个:

;with cte as
(select a,b,c,d, row_number() over (partition by d order by c,b) rn
 from your_derived_resultset)
select a,b,c,d 
from cte
where rn = 1 

答案 1 :(得分:1)

尝试此查询我的朋友:

with t1 as
(select * from table1 where D not in
(select D from table1 where c = 'j')
union all
select * from table1 where D in
(select D from table1 where c = 'j')
and c = 'j')
select a,min(b) b,c,d from t1 group by a,c,d;

SQL Fiddle

答案 2 :(得分:0)

with t (A,B,C,D)
as
(
select 81,512,'j',660 from dual
union
select 81,670,'j',660 from dual
union 
select 81,651,'n',668 from dual
union
select 81,670,'n',668 from dual
)
select * from 
(
select A,B,C,D,row_number() over (partition by D order by B) as roww
from t
) 
where roww=1

这也有效。