繁体   English   中英

我如何 select 表中的所有行,其中两列的组合在每一行(SQL Server)上都是不同的?

[英]How can I select all rows from a table where the combination of two columns is distinct on each row (SQL Server)?

我有一张这样的桌子:

用户职位

id          Name          PositionId          UserId          Code
---------------------------------------------------------------
1     |     Produce     |     1        |       1        |     A
2     |     Fruits      |     2        |       2        |     C
3     |     Grocery     |     1        |       3        |     B
4     |     Produce     |     1        |       1        |     A
5     |     Fruits      |     2        |       2        |     C
6     |     Dairy       |     4        |       8        |     F

我怎样才能 select 来自该表的所有结果,但删除 PositionId 和 UserId 组合相同的重复条目?

从本质上讲,select 语句的结果是这样的:

id          Name          PositionId          UserId          Code
---------------------------------------------------------------
1     |     Produce     |     1        |       1        |     A
2     |     Fruits      |     2        |       2        |     C
3     |     Grocery     |     1        |       3        |     B
6     |     Dairy       |     4        |       8        |     F

我想在 PositionId 和 UserId 上使用 DISTINCT 或 GROUP BY 进行过滤。 我知道我可以使用以下方法轻松获取唯一值列表:

SELECT UserId, PositionId 
FROM UsersPositions
GROUP BY UserId, PositionId

但我也想抓住其他专栏。 从我对 SO 的看法来看,我似乎想让它成为一个子查询并将其加入另一个查询。 但我该怎么做呢?

我看到了这样的事情: Finding duplicate values in a SQL table ,但它不考虑其他列。 这篇文章选择不同的组合。 INNER JOIN 有一些答案,但是当我尝试时它不能正常工作。

我认为这对我来说是一个快速的谷歌搜索,但我似乎找不到任何适用于 SQL 服务器的东西。 处理这种查询的最佳方法是什么?

这看起来是使用具有window 功能CTE的完美案例。

;with cte
as (select id, [name], positionID, UserID, Code, row_number() over(partition by positionID, UserID order by id) rn
from tbl)
select * from cte where rn=1

从您的示例数据中,除了id之外的所有四列都是相同的。 如果是这种情况,您可以使用聚合:

select max(id), Name, PositionId, UserId, Code
from t
group by Name, PositionId, UserId, Code;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM