我在表格中有17行2列。就像這樣:如何在某些Access數據中查找特定模式?
ColA ColB
---- ----
X 1
X 2
X 3
X a
Y 1
Y 2
Y a
Z 4
Z 4
Z b
Q 1
Q 2
Q 3
Q a
W 4
W b
W 5
有沒有辦法來尋找1,2,3 COLB,一個可樂的相同值的模式? 這將使我在X的輸出Q.
我在表格中有17行2列。就像這樣:如何在某些Access數據中查找特定模式?
ColA ColB
---- ----
X 1
X 2
X 3
X a
Y 1
Y 2
Y a
Z 4
Z 4
Z b
Q 1
Q 2
Q 3
Q a
W 4
W b
W 5
有沒有辦法來尋找1,2,3 COLB,一個可樂的相同值的模式? 這將使我在X的輸出Q.
你的樣品的數據顯示不同的行。在這種情況下,您可以使用此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;
下面是一個可能的解決方案:
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 ...希望,你會能夠修改上面的查詢以便能夠使用它。
(我假定你的表名爲[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
看起來這可以通過很多方式完成。我覺得這是最簡單的解決方案。感謝您的回覆。 – Kresten