mySQL:将where子句应用于所有列并按值计算结果

时间:2017-04-19 09:54:14

标签: mysql count sql-like

我有一个像这样的mySQL表

+------------+------------+------------+
|    Col1    |    Col2    |    Col3    |
+------------+------------+------------+
| wor&dA | wordB      | wordC      |
| wordD      | wordE      | wor&dF |
| wordG      | wo&rdH | wordJ      |
+------------+------------+------------+

我需要提取单元格中包含&值的所有列的所有值,并按每次出现的计数进行分组。

我目前的方法就是这个,转换键值表上的所有表并在其上应用过滤器。

SELECT field, value, count(value) as count FROM (
    SELECT "Col1" as field, Col1 as value FROM myTable
    UNION
    SELECT "Col2" as field, Col2 as value FROM myTable
    UNION
    SELECT "Col3" as field, Col3 as value FROM myTable
) as A
WHERE value LIKE '%&%'
GROUP BY 1,2

在主表中,我有大约18k记录和41列,执行时间大约是36s。执行时间不是问题,但UNION运算符似乎保留了唯一对(字段值),因此GROUP BY操作无用

我正在寻找的输出就是这个。对于每个字段 - 值对,计数值(如果我在同一列中包含&的不同值,则需要此值)

+-------+------------+-------+
| field |   value    | count |
+-------+------------+-------+
| Col1  | wor&dA |     1 |
| Col2  | wo&rdH |     1 |
| Col3  | wor&dF |     1 |
+-------+------------+-------+

如何进行此查询以将输出格式化为示例?

2 个答案:

答案 0 :(得分:0)

SELECT SUM(Col1COUNT) Col1COUNT,SUM(Col2COUNT) Col2COUNT,SUM(Col3COUNT) Col3COUNT FROM (
    SELECT 
    CASE WHEN COL1 LIKE '%&%' THEN 1 ELSE 0 END  Col1COUNT ,
    CASE WHEN COL2 LIKE '%&%' THEN 1 ELSE 0 END  Col2COUNT ,
    CASE WHEN COL3 LIKE '%&%' THEN 1 ELSE 0 END  Col3COUNT 
    FROM myTable
)Z
;

 SELECT GROUP_CONCAT(Col1VAL) Col1VAL ,SUM(Col1COUNT) Col1COUNT,
        GROUP_CONCAT(Col2VAL) Col2VAL,SUM(Col2COUNT) Col2COUNT,
        GROUP_CONCAT(Col3VAL) Col3VAL,SUM(Col3COUNT) Col3COUNT FROM (
        SELECT 
        CASE WHEN COL1 LIKE '%&%' THEN 1 ELSE 0 END  Col1COUNT ,
        CASE WHEN COL2 LIKE '%&%' THEN 1 ELSE 0 END  Col2COUNT ,
        CASE WHEN COL3 LIKE '%&%' THEN 1 ELSE 0 END  Col3COUNT ,
        CASE WHEN COL1 LIKE '%&%' THEN VALUE END  Col1VAL ,
        CASE WHEN COL2 LIKE '%&%' THEN VALUE END  Col2VAL,
        CASE WHEN COL3 LIKE '%&%' THEN VALUE END  Col3VAL

        FROM myTable
    )Z
    ;

试试上面的代码。

希望这会有所帮助。

答案 1 :(得分:-1)

UNION可以消除重复,因此您只需计算一次出现的次数。请改用UNION ALL

SELECT field, value, count(*) as "count" FROM (
    SELECT "Col1" as field, Col1 as value FROM myTable
    UNION ALL
    SELECT "Col2" as field, Col2 as value FROM myTable
    UNION ALL
    SELECT "Col3" as field, Col3 as value FROM myTable
) as A
WHERE value LIKE '%&%'
GROUP BY 1,2;