我在emp表中有这些数据:
id |dbname
1 |db1
2 |db1
1 |db1
2 |db2
3 |db2
5 |db2
1 |db2
4 |db3
1 |db3
3 |db3
Emp表有数据库相关记录(db1,db2,db3 ......等),如果在不同的数据库(db1,db2,db3等)中存在相同的id,那么我需要检索第一个dbname。基于上面的表数据,我想要输出如下
Id | dbname
1 | db1
2 | db1
3 | db2
5 | db2
4 | db3
答案 0 :(得分:1)
请尝试此解决方案:
create table #empTable (ID INT, DBName varchar(10))
insert into #empTable values (1,'db1'), (2,'db1'), (1,'db1'), (2,'db2'), (3,'db2'), (5,'db2'), (1,'db2'), (4,'db3'), (1,'db3'), (3,'db3')
select a.ID, a.DBName
from
(
select e.*, ROW_NUMBER() over (partition by ID order by ID) as Rnk
from #empTable e
) a
where a.Rnk = 1
答案 1 :(得分:0)
假设第一个数据库意味着按字母顺序排列:
您可以使用MIN
功能:
SELECT
Id,
MIN(dbname) AS dbname
FROM emp
GROUP BY Id
或ROW_NUMBER
:
SELECT
Id, dbname
FROM(
SELECT *, RN = ROW_NUMBER() OVER(PARTITION BY Id ORDER BY dbname)
FROM emp
)t
WHERE RN = 1
答案 2 :(得分:0)
我尝试下面查询给出正确的结果。任何人请分享任何不同的方式。谢谢!
;with abc as
(select * , ROW_NUMBER()over(partition by id order by dbname) as b
from [Test].[dbo].[test123])
select id,dbname from abc where b=1