2017-10-13 110 views
0

任何人有任何想法可以更好地寫這段代碼?寫更好的方法:SELECT * COUNT> 1

SELECT Column_A, Column_B, Column_C, Column_D, Column_E 
FROM TABLE_A 
WHERE Column_A IN 
(
    SELECT Column_A 
    FROM 
    (
    SELECT Column_A, COUNT(DISTINCT COLUMN_B) AS Column_B_Count 
    FROM TABLE_A 
    GROUP by Column_A 
    HAVING Column_B_Count > 1 
    ) AS A 
) 
GROUP BY Column_A, Column_B, Column_C, Column_D, Column_E; 

謝謝!

+0

無論何時您選擇GROUP BY時,您選擇的每一列其實都意味着'DISTINCT',儘管在5列開始看起來很可疑。您可以在'HAVING'子句之後放置聚合函數(如'COUNT'),這意味着您可以從'SELECT'列表中移除它並擺脫中間子查詢。除此之外,我們需要更多關於您的表格/數據的信息。 –

回答

0
SELECT DISTINCT 
    A.Column_A 
    , A.Column_B 
    , A.Column_C 
    , A.Column_D 
    , A.Column_E 
FROM 
    TABLE_A AS A 
    JOIN 
     (
      SELECT Column_A 
      FROM TABLE_A 
      GROUP by Column_A 
      HAVING COUNT(DISTINCT COLUMN_B) > 1 
     ) AS Column_B_Count 
    ON A.Column_A = Column_B_Count.Column_A 
+1

從技術上講,不,因爲原來最外面的'GROUP BY'會刪除任何重複項(儘管在5列我自己有點懷疑)。 –

+0

感謝您指出 - 我添加了「DISTINCT」。 :) –

+1

',COUNT(DISTINCT COLUMN_B)如果您只是使用'HAVING COUNT(DISTINCT COLUMN_B)> 1',而不是通過'having'子句中的列別名引用,那麼可以省略Column_B_Count'。 –

0
SELECT Distinct Column_A, 
     Column_B, 
     Column_C, 
     Column_D, 
     Column_E 
FROM TABLE_A 
WHERE Column_A IN 
    (
    SELECT Column_A 
    FROM TABLE_A 
    GROUP by Column_A 
    HAVING COUNT(DISTINCT COLUMN_B) > 1 
    ) 
0

我會用窗口的功能。我認爲這是你想要什麼:

select . . . 
from (select a.*, 
      min(column_b) over (partition by a) as min_b, 
      max(column_b) over (partition by a) as max_b, 
     from table_a a 
    ) a 
where min_b <> max_b; 

您可能仍然需要select distinct,如果該查詢可以返回重複。

0
SELECT DISTINCT -- same as the final GROUP BY of original query 
    Column_A, Column_B, Column_C, Column_D, Column_E 
FROM TABLE_A 
    -- 
GROUP BY Column_A, Column_B, Column_C, Column_D, Column_E 
QUALIFY -- emulating DISTINCT > 1, which is not allowed in Windowed Aggregates: 
    MIN(COLUMN_B) OVER (PARTITION BY Column_A) 
<> MAX(COLUMN_B) OVER (PARTITION BY Column_A) 

取決於實際數據,即低數量的每個組重複的,它可能是更有效的除去GROUP BY

相關問題