[英]How can I select all rows from a table where the combination of two columns is distinct on each row (SQL Server)?
I have a table like this:我有一张这样的桌子:
UsersPositions用户职位
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
How can I select all results from this table, but remove duplicate entries in which the combination of PositionId and UserId is the same?我怎样才能 select 来自该表的所有结果,但删除 PositionId 和 UserId 组合相同的重复条目?
Where essentially, the result of the select statement would be this:从本质上讲,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
I want to filter using DISTINCT or GROUP BY on PositionId and UserId.我想在 PositionId 和 UserId 上使用 DISTINCT 或 GROUP BY 进行过滤。 I know I can easily get a list of unique values using:
我知道我可以使用以下方法轻松获取唯一值列表:
SELECT UserId, PositionId
FROM UsersPositions
GROUP BY UserId, PositionId
But I also want to grab the other columns.但我也想抓住其他专栏。 From what I've looked on SO, it seems like I would want to make this a subquery and join it into another query.
从我对 SO 的看法来看,我似乎想让它成为一个子查询并将其加入另一个查询。 But how can I do that?
但我该怎么做呢?
I saw something like this: Finding duplicate values in a SQL table , but it doesn't account for other columns.我看到了这样的事情: Finding duplicate values in a SQL table ,但它不考虑其他列。 This post Selecting Distinct combinations.
这篇文章选择不同的组合。 has a few answers with INNER JOIN, but it doesn't work correctly when I try that.
INNER JOIN 有一些答案,但是当我尝试时它不能正常工作。
I thought this would be a quick google search for me, but I can't seem to find anything that works on SQL Server.我认为这对我来说是一个快速的谷歌搜索,但我似乎找不到任何适用于 SQL 服务器的东西。 What's the best way to handle this kind of query?
处理这种查询的最佳方法是什么?
This looks like a perfect case to use a CTE with window funtions .这看起来是使用具有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
From your sample data, all four columns other than id
are the same.从您的示例数据中,除了
id
之外的所有四列都是相同的。 If that is the case, you can use aggregation:如果是这种情况,您可以使用聚合:
select max(id), Name, PositionId, UserId, Code
from t
group by Name, PositionId, UserId, Code;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.