Return 不同的行仅基于 oracle 中的一列 sql
Return distinct rows based on only one column in oracle sql
我想要 return n 个不同的行。不同的行应仅基于一列 (SN)。
我有下面的查询,预计 return 4 行序列号大于 2 并且没有具有相似 SN 列值的行被 returned。
Table
SN letter value
1 test 25
1 bread 26
3 alpha 43
4 beta 23
4 gamma 5
5 omega 60
6 omega 60
预期结果
SN letter value
3 alpha 43
4 beta 23
5 omega 60
6 omega 60
这是我的查询。这不能正常工作,它 return 是重复项,因为它通过组合的所有列而不是单个列 SN 过滤不同的值。
SELECT * FROM (SELECT a.*, row_number() over(order by SN) rowRank
FROM (SELECT distinct SN, letter, value from table where SN > 2 order by SN) a)
WHERE rowRank BETWEEN 1 AND 4}"
您无需使用 DISTINCT
即可尝试过滤掉您的结果。如果您需要修改应该返回 SN
的哪个副本,您可以修改 row_rank
分析函数的 ORDER BY
子句。现在它按字母顺序返回第一个 LETTER
值,因为它与您的示例结果匹配。
查询
WITH
some_table (sn, letter, VALUE)
AS
(SELECT 1, 'test', 25 FROM DUAL
UNION ALL
SELECT 1, 'bread', 26 FROM DUAL
UNION ALL
SELECT 3, 'alpha', 43 FROM DUAL
UNION ALL
SELECT 4, 'beta', 23 FROM DUAL
UNION ALL
SELECT 4, 'gamma', 5 FROM DUAL
UNION ALL
SELECT 5, 'omega', 60 FROM DUAL
UNION ALL
SELECT 6, 'omega', 60 FROM DUAL)
--Above is to set up the sample data. Use the query below with your real table
SELECT sn, letter, VALUE
FROM (SELECT sn,
letter,
VALUE,
ROW_NUMBER () OVER (PARTITION BY sn ORDER BY letter) AS row_rank
FROM some_table
WHERE sn > 2)
WHERE row_rank = 1
ORDER BY sn
FETCH FIRST 4 ROWS ONLY;
结果
SN LETTER VALUE
_____ _________ ________
3 alpha 43
4 beta 23
5 omega 60
6 omega 60
SELECT * FROM
(
SELECT
t.*
,ROW_NUMBER() OVER (PARTITION BY sn ORDER BY value ) rn
FROM
t
WHERE sn > 2
) t1
WHERE t1.rn = 1
ORDER BY sn;
我想要 return n 个不同的行。不同的行应仅基于一列 (SN)。
我有下面的查询,预计 return 4 行序列号大于 2 并且没有具有相似 SN 列值的行被 returned。
Table
SN letter value
1 test 25
1 bread 26
3 alpha 43
4 beta 23
4 gamma 5
5 omega 60
6 omega 60
预期结果
SN letter value
3 alpha 43
4 beta 23
5 omega 60
6 omega 60
这是我的查询。这不能正常工作,它 return 是重复项,因为它通过组合的所有列而不是单个列 SN 过滤不同的值。
SELECT * FROM (SELECT a.*, row_number() over(order by SN) rowRank
FROM (SELECT distinct SN, letter, value from table where SN > 2 order by SN) a)
WHERE rowRank BETWEEN 1 AND 4}"
您无需使用 DISTINCT
即可尝试过滤掉您的结果。如果您需要修改应该返回 SN
的哪个副本,您可以修改 row_rank
分析函数的 ORDER BY
子句。现在它按字母顺序返回第一个 LETTER
值,因为它与您的示例结果匹配。
查询
WITH
some_table (sn, letter, VALUE)
AS
(SELECT 1, 'test', 25 FROM DUAL
UNION ALL
SELECT 1, 'bread', 26 FROM DUAL
UNION ALL
SELECT 3, 'alpha', 43 FROM DUAL
UNION ALL
SELECT 4, 'beta', 23 FROM DUAL
UNION ALL
SELECT 4, 'gamma', 5 FROM DUAL
UNION ALL
SELECT 5, 'omega', 60 FROM DUAL
UNION ALL
SELECT 6, 'omega', 60 FROM DUAL)
--Above is to set up the sample data. Use the query below with your real table
SELECT sn, letter, VALUE
FROM (SELECT sn,
letter,
VALUE,
ROW_NUMBER () OVER (PARTITION BY sn ORDER BY letter) AS row_rank
FROM some_table
WHERE sn > 2)
WHERE row_rank = 1
ORDER BY sn
FETCH FIRST 4 ROWS ONLY;
结果
SN LETTER VALUE
_____ _________ ________
3 alpha 43
4 beta 23
5 omega 60
6 omega 60
SELECT * FROM
(
SELECT
t.*
,ROW_NUMBER() OVER (PARTITION BY sn ORDER BY value ) rn
FROM
t
WHERE sn > 2
) t1
WHERE t1.rn = 1
ORDER BY sn;