Distinct

SELECT DISTINCT 兩列沒有範圍

  • January 22, 2019

如何選擇不正確排列的不同兩列。例如:如果我有這張桌子 t:

================
|| a   || b   ||
=======||=======
|| 1   || 2   ||  
|| 1   || 3   ||
|| 2   || 3   ||
|| 3   || 1   ||
|| 2   || 1   ||
================

如果我在查詢中選擇 1,結果應該是:

================
|| a   || b   ||
=======||=======
|| 1   || 2   ||  
|| 1   || 3   ||
================

該表是選擇具有 a=1 或 b=1 且不重複 a、b 或相反的行的結果。 細節:

結果SELECT * FROM t WHERE a=1 OR b=1;將是:

================
|| a   || b   ||
=======||=======
|| 1   || 2   ||  
|| 1   || 3   ||
|| 3   || 1   ||
|| 2   || 1   ||
================

我應該正常和相反地消除重複的行。

|| 2 || 1 ||將被淘汰,因為它的倒數|| 1 || 2 ||

|| 3 || 1 ||將被淘汰,因為它的倒數|| 1 || 3 ||

結果如上所示。

Jon of All Trades在他的回答中提到的更有效(而且更短)的版本可能是這樣的:

SELECT DISTINCT 
CASE WHEN A < B THEN A ELSE B END AS value1,
CASE WHEN A < B THEN B ELSE A END AS value2
FROM T

當然,如果您只需要檢查包含 的元組1,您可以添加類似WHERE A = 1 OR B = 1

所以輸出應該是 { 1, 2 } 和 { 1, 3 }?我確信有一種更有效的方法可以做到這一點,但如果您只需要一個快速而簡單的解決方案,這應該適用於 SQL Server:

SELECT
   LEFT(Concatenated, CHARINDEX('|', Concatenated) - 1),
   SUBSTRING(Concatenated, CHARINDEX('|', Concatenated) + 1, 999)
FROM
   (
   SELECT DISTINCT
       CASE 
           WHEN A < B 
           THEN CAST(A AS VARCHAR(10)) + '|' + CAST(B AS VARCHAR(10)) 
           ELSE CAST(B AS VARCHAR(10)) + '|' + CAST(A AS VARCHAR(10)) 
       END AS Concatenated
   FROM
       T
   WHERE
       A = 1 OR B = 1
   ) AS X

引用自:https://dba.stackexchange.com/questions/131743