我有下表
Id Stack
------------------
1 a
1 b
2 c
2 d
我想得到下表结果。
Id Stack
------------------
1 a
2 c
我使用 DISTINCT 但它不起作用我该怎么做?有没有使用 group by 的解决方案?
我有下表
Id Stack
------------------
1 a
1 b
2 c
2 d
我想得到下表结果。
Id Stack
------------------
1 a
2 c
我使用 DISTINCT 但它不起作用我该怎么做?有没有使用 group by 的解决方案?
CREATE table sampletb(id int, stack varchar(10));
INSERT into sampletb values(1,'a');
INSERT into sampletb values(1,'b');
INSERT into sampletb values(2,'c');
INSERT into sampletb values(2,'d');
SELECT * FROM sampletb;
id stack
----------- ----------
1 a
1 b
2 c
2 d
SELECT id,
stack,
row_number() over (partition by id order by stack) as row_number
from sampletb;
这个查询会给你这样的结果。
id stack row_number
----------- ---------- --------------------
1 a 1
1 b 2
2 c 1
2 d 2
现在将上述查询作为子查询并获取具有的列
row_number=1
将给出您想要的输出。
select id,stack from
(
SELECT id,
stack,
row_number() over (partition by id order by stack) as row_number
FROM sampletb) x
where x.row_number=1;
id stack
----------- ----------
1 a
2 c
select id,stack from (
select id , stack , row_number() over (partition by id order by stack) as rn
) k where rn=1
我不确定您需要应用的确切逻辑,但这将返回您发布的结果:
SELECT ID, MIN(Stack) AS Stack
FROM T
GROUP BY ID
如果您的 DBMS 允许,您可以对函数使用更高级的逻辑ROW_NUMBER
(问题中没有标记)
SELECT ID, Stack
FROM ( SELECT ID,
Stack,
ROW_NUMBER() OVER(PARTITION BY ID ORDER BY Stack) AS RowNumber
FROM T
) t
WHERE RowNumber = 1
这应该有帮助
select Id, min(Stack) from <TABLE_NAME>
group by Id