1

我的表格中有 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 的输出。

4

3 回答 3

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;
于 2013-10-14T13:44:10.227 回答
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   
于 2013-10-14T13:02:37.897 回答
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 ...希望您能够修改上述查询以使用它。

于 2013-10-14T07:19:52.667 回答