我需要您提供独特查询的帮助。我有下面的查询返回表的所有不同的值,但我也希望看到其余的列,而不仅仅是不同的列。我怎么能这样做?
我尝试了几项更改,但无法正常工作。使用Oracle和SQL Developer。
select distinct field1 from table1
where field2 in ('A','B','C')
答案 0 :(得分:1)
您想如何选择其他值?以下是一些选项:
Oracle安装程序:
CREATE TABLE table1 ( field1, field2, field3 ) AS
SELECT 1, 'A', 1 FROM DUAL UNION ALL
SELECT 1, 'A', 2 FROM DUAL UNION ALL
SELECT 1, 'B', 3 FROM DUAL UNION ALL
SELECT 1, 'C', 1 FROM DUAL UNION ALL
SELECT 2, 'A', 1 FROM DUAL UNION ALL
SELECT 2, 'C', 1 FROM DUAL UNION ALL
SELECT 2, 'A', 3 FROM DUAL UNION ALL
SELECT 3, 'B', 3 FROM DUAL UNION ALL
SELECT 3, 'B', 2 FROM DUAL UNION ALL
SELECT 3, 'B', 1 FROM DUAL;
查询1 - 获取第一行:
SELECT field1, field2, field3
FROM (
SELECT t.*,
ROW_NUMBER() OVER ( PARTITION BY field1 ORDER BY ROWNUM ) AS rn
FROM table1 t
WHERE field2 IN ( 'A', 'B', 'C' )
)
WHERE rn = 1;
输出1 :
FIELD1 FIELD2 FIELD3
---------- ------ ----------
1 A 1
2 A 1
3 B 3
查询2 - 获取field1
的最大值:
SELECT field1,
MAX( field2 ) AS field2,
MAX( field3 ) AS field3
FROM table1 t
WHERE field2 IN ( 'A', 'B', 'C' )
GROUP BY field1;
输出2 :
FIELD1 FIELD2 FIELD3
---------- ------ ----------
1 C 3
2 C 3
3 B 3
注意:前2个输出行与原始数据中的任何行都不匹配,因为最大值来自不同的行。
查询3 - 获取最大field2
和相应的最大field3
值:
SELECT field1,
MAX( field2 ) AS field2,
MAX( field3 ) KEEP ( DENSE_RANK LAST ORDER BY Field2 ) AS field3
FROM table1 t
WHERE field2 IN ( 'A', 'B', 'C' )
GROUP BY field1;
或
SELECT field1, field2, field3
FROM (
SELECT t.*,
ROW_NUMBER() OVER ( PARTITION BY field1 ORDER BY field2 DESC, field3 DESC ) AS rn
FROM table1 t
WHERE field2 IN ( 'A', 'B', 'C' )
)
WHERE rn = 1;
输出3 :
FIELD1 FIELD2 FIELD3
---------- ------ ----------
1 C 1
2 C 1
3 B 3
答案 1 :(得分:0)
你想要这样的东西吗?
select distinct * from table1 where field2 in ('A','B','C')
答案 2 :(得分:0)
所以,理论上,你不能做你想的。原因是当你使用distinct子句时,所有列出的字段都被认为是不同的,因为一个字段可以假设2个不同的值,但该字段上一个单独值的其他字段也可以采用不同的值。
答案 3 :(得分:-1)
如果您希望每field1
个值占一行,请使用row_number()
:
select t.*
from (select t1.*,
row_number() over (partition by field1 order by field1) as seqnum
from table1 t1
where field2 in ('A','B','C')
) t;