如果存在相同的标识符,我如何 select 的前 1 个结果? SQL 服务器
How do I select the top 1 results of the if the same identifier exist? SQL Server
我在 sql 服务器 2008 中有一个数据 table,我想 select 每个标识符中的前 1 个:
之前和之后的结果应该是这样的:
因此,如果确实存在相同的标识符,它应该只 select 第一个结果。非常感谢。
只是区分它们:
select distinct [primary identifier] from tablename
或分组:
select [primary identifier] from tablename group by [primary identifier]
如果存在更多列,您可以使用 window 函数对行进行排名:
;with cte as(select *, row_number() over(partition by [primary identifier] order by (select null)) rn from tablename)
select * from cte where rn = 1
将 order by (select null)
更改为适当的排序栏。
select distinct [Primary Identifier] from tbl
如果您有完整的记录(其他列)而不是那一列,您可以对它们进行行编号并选择一个。
select {list of columns}
from
(
select *, rn = row_number over (partition by [Primary Identifier]
order by 1/0)
from tbl
) X
where rn = 1;
order by 1/0
是任意的。如果您需要从 "duplicates" 中选择一个特定的,例如最高的 cost
,您可以按 cost descending
排序,即
(partition by [Primary Identifier]
order by [cost] descending)
我认为这将是满足您需求的合适解决方案-
;WITH cte AS
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY [Primary Identifier] ORDER BY [sort columns]) AS rowid
FROM [table]
)
SELECT *
FROM cte
WHERE rowid = 1
我在 sql 服务器 2008 中有一个数据 table,我想 select 每个标识符中的前 1 个:
之前和之后的结果应该是这样的:
因此,如果确实存在相同的标识符,它应该只 select 第一个结果。非常感谢。
只是区分它们:
select distinct [primary identifier] from tablename
或分组:
select [primary identifier] from tablename group by [primary identifier]
如果存在更多列,您可以使用 window 函数对行进行排名:
;with cte as(select *, row_number() over(partition by [primary identifier] order by (select null)) rn from tablename)
select * from cte where rn = 1
将 order by (select null)
更改为适当的排序栏。
select distinct [Primary Identifier] from tbl
如果您有完整的记录(其他列)而不是那一列,您可以对它们进行行编号并选择一个。
select {list of columns}
from
(
select *, rn = row_number over (partition by [Primary Identifier]
order by 1/0)
from tbl
) X
where rn = 1;
order by 1/0
是任意的。如果您需要从 "duplicates" 中选择一个特定的,例如最高的 cost
,您可以按 cost descending
排序,即
(partition by [Primary Identifier]
order by [cost] descending)
我认为这将是满足您需求的合适解决方案-
;WITH cte AS
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY [Primary Identifier] ORDER BY [sort columns]) AS rowid
FROM [table]
)
SELECT *
FROM cte
WHERE rowid = 1