使用sql查询获取记录组合

时间:2014-07-24 07:41:12

标签: sql oracle

我需要一个获取记录的查询

1 A
1 P
1 D
1 A
2 A
2 D
2 A
3 A
3 A
3 A
4 A
4 D
4 A
4 D

我想选择A和D组合记录。  那是我需要选择的 2 A. 2 D. 2 A. 4 A. 4 D. 4 A. 4 D.  但我不想选择1和3条记录  你能帮我吗?

3 个答案:

答案 0 :(得分:0)

试试这个

Select * from table where column2_name in ('A','D') and column1_name = 2

这将给出包含A和D的记录。

Select * from table where column2_name in ('A','D') 
and column1_name = (Select max(column1_name) 
                     from table where column2_name in ('A','D'))

答案 1 :(得分:0)

试试这个:

select * from yourtable where column1 in 
( 
 select column1
 from yourtable
 group by column1
 having count(distinct column2) = 2 -- Only 2 different values should be possible
 and max(column2) = 'D' 
 and min(column2) = 'A' --Useful if B or C are possible values)

答案 2 :(得分:0)

SELECT * FROM table
WHERE (column2 = 'A' OR column2 = 'D') AND MOD(column1, 2) = 0