我有一个包含以下数据的表格。
id country serial other_column
1 us 123 1
2 us 456 1
3 gb 123 1
4 gb 456 1
5 jp 777 1
6 jp 888 1
7 us 123 2
8 us 456 3
9 gb 456 4
10 us 123 1
11 us 123 1
有没有办法为每个唯一的国家/地区和唯一的序列获取 2 行?
例如,我的查询期望得到以下结果。
us,123,1 出现两次,因为有 3 个同类,我希望每个唯一的国家/地区和唯一的序列有 2 行。
us,123,1
us,123,1
us,456,1
gb,123,1
gb,456,1
jp,777,1
jp,888,1
我无法使用:
select distinct country, serial from my_table;
因为我想要每个不同值匹配 2 行国家/地区和序列号。请指教。
最佳答案
使用 DENSE_RANK
或 ROW_NUMBER
将 CTE
和 subquery
分配给您的数据集,然后返回 ROW_NUMBER
小于 3
且 DENSE_RANK
等于 1
的行。另外,由于您没有指定 ORDERING
,因此我添加了一个自定义 ORDER BY
来处理您的 Country
排序,以匹配您上面所需的输出。
SELECT
ID,
Country,
Serial,
other_column
FROM
(SELECT
*,
ROW_NUMBER() OVER (PARTITION BY Country, Serial ORDER BY Country, Serial, other_column) AS RN,
DENSE_RANK() OVER (PARTITION BY Country, Serial ORDER BY Country, Serial, other_column) AS DR
FROM my_table) A
WHERE RN < 3 AND DR = 1
ORDER BY CASE WHEN Country = 'us' THEN 1
WHEN Country = 'gb' THEN 2
WHEN Country = 'jp' THEN 3
ELSE 4
END ASC, Country, Serial, other_column, ID
结果:
| ID | Country | Serial | other_column |
|----|---------|--------|---------------|
| 1 | us | 123 | 1 |
| 10 | us | 123 | 1 |
| 2 | us | 456 | 1 |
| 3 | gb | 123 | 1 |
| 4 | gb | 456 | 1 |
| 5 | jp | 777 | 1 |
| 6 | jp | 888 | 1 |
拨弄 here 。
关于sql - 选择多个不同的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74275837/