簡體   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