簡體   English   中英

選擇DISTINCT多列

[英]Select DISTINCT multiple columns

我在檢索DISTINCT記錄時遇到了麻煩。 方案如下:現在我的查詢是

Select a,b,c from TABLE_NAME
(COMPLEX_INNER JOIN LOGIC)

我想要前兩列值應該唯一的記錄。 我知道這可以通過

GROUP BY 

條款。 因此查詢將變為

Select a,b,c from TABLE_NAME
(COMPLEX_INNER JOIN LOGIC)
GROUP BY a,b

但是由於c沒有出現在SQL Server的聚合函數或分組中,因此出現以下錯誤:

在選擇列表中,列“ c”無效,因為列既未包含在聚合函數中,也未包含在GROUP BY子句中。

您可以將查詢放在CTE中,並使用row_number()函數確定要提取的行。
像這樣:

with C as
(
  Select a,b,c,
         row_number() over(partition by a, b order by SomeColumn) as rn
  from TABLE_NAME
  --(COMPLEX_INNER JOIN LOGIC)
)
select a, b, c
from C
where rn = 1

工作樣本:

declare @T table
(
  a int,
  b int,
  c int
)

insert into @T values
(1, 1, 1),
(1, 1, 2),
(2, 2, 1),
(2, 2, 2)

;with C as
(
  select a, b, c,
         row_number() over(partition by a, b order by c) as rn
  from @T         
)
select a, b, c
from C
where rn = 1

結果:

a           b           c
----------- ----------- -----------
1           1           1
2           2           1

這樣使用

select c,q.a,q.b from TABLE_NAME inner join 
(
Select a,b from TABLE_NAME
(COMPLEX_INNER JOIN LOGIC)
GROUP BY a,b) q 
on q.a=TABLE_NAME.a

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM