我有一个包含重复 ID 的表,稍后我会修复它。基本上我想返回 ID 不同的所有行,但我想要整行。像这样的东西:
select * from table group by ID
select * from table where (ID is not repeated)
在这种情况下,它们是相同的行,所以我不关心它是第一个还是最后一个,最小值还是最大值。
请注意,我不想这样做:
select MIN(col1), MIN(col2), ... from table group by ID
我想要一种无需枚举每一列即可获得此结果的方法。
编辑:我使用的是 SQL Server 2008 R2。
最佳答案
如果您使用的是 MySql,请执行以下操作:
select
*
from tbl
group by ID
MySQL 实时测试:http://www.sqlfiddle.com/#!2/8c7fd/2
如果您使用的是 Postgresql,请执行以下操作:
select distinct on(id)
*
from tbl
order by id
如果您希望 Postgresql DISTINCT ON 至少与 CTE 窗口函数一样可预测。对另一列进行排序:
select distinct on(id)
*
from tbl
order by id
, someColumnHere -- Choose ASC for first row, DESC for last row
Postgresql 实时测试:http://www.sqlfiddle.com/#!1/8c7fd/1
如果您使用的是支持 CTE 窗口的数据库(例如 Postgres、Oracle、Sql Server),请使用:
with ranked as
(
select
rank() over(partition by id order by column) rn,
*
from tbl
)
select * from ranked where rn = 1
CTE 窗口化数据库:
Posgtresql:http://www.sqlfiddle.com/#!1/8c7fd/2
关于SQL 服务器 : How do I return all columns where one is not repeated?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10440796/