我有一个带值的表
ID Number
1 6
2 6
3 7
4 7
5 1
6 1
7 2
8 2
我为不同的数字写了一个选择查询
SELECT DISTINCT Number FROM Table
我的输出就像
ID Number
1 1
2 2
3 6
4 7
但我想输出
ID Number
1 6
2 7
3 1
4 2
我怎样才能带来这样的输出?
答案 0 :(得分:2)
您可以使用ROW_NUMBER
等窗口函数:
WITH cte AS
(
SELECT Number, MAX(ID) AS max_ID
FROM #Tab
GROUP BY Number
)
SELECT ROW_NUMBER() OVER(ORDER BY max_ID) AS ID, Number
FROM cte
ORDER BY max_ID
的 LiveDemo
强>
输出:
╔════╦════════╗
║ ID ║ Number ║
╠════╬════════╣
║ 1 ║ 6 ║
║ 2 ║ 7 ║
║ 3 ║ 1 ║
║ 4 ║ 2 ║
╚════╩════════╝
答案 1 :(得分:0)
因此,您要删除重复的Numbers
并按ID
保留排序。
一种可能的方法是使用ROW_NUMBER
:
DECLARE @T TABLE ([ID] int, [Number] int);
INSERT INTO @T ([ID], [Number]) VALUES
(1, 6),
(2, 6),
(3, 7),
(4, 7),
(5, 1),
(6, 1),
(7, 2),
(8, 2);
WITH
CTE
AS
(
SELECT
ID
,Number
,ROW_NUMBER() OVER (PARTITION BY Number ORDER BY ID) AS rn
FROM @T AS T
)
SELECT
ID
,Number
FROM CTE
WHERE rn = 1
ORDER BY ID;
<强>结果强>
ID Number
1 6
3 7
5 1
7 2