如何在某些Access数据中查找特定模式?

时间:2013-10-14 07:07:25

标签: sql ms-access pattern-matching

我的表格中有前17行和2列。像这样:

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   

有没有办法在colB中寻找1,2,3的模式,a对于相同的ColA值? 那会给我输出X和Q.

3 个答案:

答案 0 :(得分:1)

(我假设您的表名为[PatternData]。)

如果您使用Allen Browne的ConcatRelated函数,您可以创建一个查询,以“串联”[ColA]的每个不同值的所有[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        

然后您可以使用上述查询作为查询的基础,以查找具有所需模式的[ColA]值

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   

答案 1 :(得分: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;

答案 2 :(得分: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
             )
;

编辑:操作,由于某种原因,我认为您使用的是Oracle ...希望您能够修改上述查询以便能够使用它。