2013-10-14 59 views

回答

1

你的樣品的數據顯示不同的行。在這種情況下,您可以使用此GROUP BY查詢。

SELECT y.ColA 
FROM YourTable AS y 
WHERE y.ColB In ('1','2','3','a') 
GROUP BY y.ColA 
HAVING Count(*) = 4; 

如果實際數據可能包括重複的行,你可以用SELECT DISTINCT在子查詢應用GROUP BY之前啓動。

SELECT sub.ColA 
FROM 
    (
     SELECT DISTINCT y.ColA, y.ColB 
     FROM YourTable AS y 
     WHERE y.ColB In ('1','2','3','a') 
    ) AS sub 
GROUP BY sub.ColA 
HAVING Count(*) = 4; 
+0

看起來這可以通過很多方式完成。我覺得這是最簡單的解決方案。感謝您的回覆。 – Kresten

0

下面是一個可能的解決方案:

WITH 
    data AS (
    SELECT 'X' cola, '1' colb FROM dual 
    UNION ALL SELECT 'X' cola, '2' FROM dual 
    UNION ALL SELECT 'X', '3' FROM dual 
    UNION ALL SELECT 'X', 'a' FROM dual 
    UNION ALL SELECT 'Y', '1' FROM dual 
    UNION ALL SELECT 'Y', '2' FROM dual 
    UNION ALL SELECT 'Y', 'a' FROM dual 
    UNION ALL SELECT 'Z', '4' FROM dual 
    UNION ALL SELECT 'Z', '4' FROM dual 
    UNION ALL SELECT 'Z', 'b' FROM dual 
    UNION ALL SELECT 'Q', '1' FROM dual 
    UNION ALL SELECT 'Q', '2' FROM dual 
    UNION ALL SELECT 'Q', '3' FROM dual 
    UNION ALL SELECT 'Q', 'a' FROM dual 
    UNION ALL SELECT 'W', '4' FROM dual 
    UNION ALL SELECT 'W', '5' FROM dual 
    UNION ALL SELECT 'W', 'b' FROM dual 
), 
    data_agg AS (
    SELECT cola, listagg(colb) WITHIN GROUP (ORDER BY colb) AS agg_colb 
     FROM data 
    GROUP BY cola 
) 
SELECT cola 
    FROM data_agg da 
WHERE EXISTS (SELECT 1 
       FROM data_agg 
       WHERE cola != da.cola 
       AND agg_colb = da.agg_colb 
      ) 
; 

編輯:OPS,由於某種原因,我還以爲你使用的是Oracle ...希望,你會能夠修改上面的查詢以便能夠使用它。

1

(我假定你的表名爲[PatternData]。)

如果使用艾倫·布朗的ConcatRelated功能,您可以創建一個查詢來「串起來」的所有[COLB]值的的[可口可樂]這樣每個不同的值...

SELECT 
    ColA, 
    ConcatRelated("ColB", "PatternData", "ColA=""" & ColA & """" , "ColB", "") AS ColB_values 
FROM (SELECT DISTINCT ColA FROM PatternData) 

... ...返回

ColA ColB_values 
---- ----------- 
Q  123a  
W  45b   
X  123a  
Y  12a   
Z  44b   

然後你就可以使用上面的查詢作爲查詢的基礎上找到[可樂]值與期望的圖案

SELECT ColA 
FROM 
    (
     SELECT 
      ColA, 
      ConcatRelated("ColB", "PatternData", "ColA=""" & ColA & """" , "ColB", "") AS ColB_values 
     FROM (SELECT DISTINCT ColA FROM PatternData) 
    ) 
WHERE ColB_values = "123a" 

...返回...

ColA 
---- 
Q 
X 
相關問題