0

我有一个非规范化表,我必须计算其他列中相同值的数量。我正在使用 InfiniDB Mysql 存储引擎。

这是我的表:

col1 | col2 | col3
------------------
A    | B    | B
A    | B    | C
A    | A    | A

这就是我所期望的:

col1Values | col2Values | col3Values
------------------------------------
    1      |     2      |      2     -- Because B is in Col2 and Col3
    1      |     1      |      1     
    3      |     3      |      3

有没有类似的东西

-- function count_values(needle, haystack1, ...haystackN)
select count_values(col1, col1, col2, col3) as col1values -- col1 is needle
    , count_values(col2, col1, col2, col3) as col2values -- col2 is needle
    , count_values(col3, col1, col2, col3) as col3values -- col3 is needle
from table

还是我错过了一些可以解决问题的简单方法?:-)

提前致谢

罗马

4

3 回答 3

1
     select 
        CASE WHEN col1 = col2 and col1=col3 THEN '3' 
             WHEN col1 = col2 or col1=col3 THEN '2' 
             WHEN col1 != col2 and col1!=col3 THEN '1' 
        ELSE '0' END AS col1_values, 

        CASE WHEN col2 = col1 and col2=col3 THEN '3' 
             WHEN col2 = col1 or col2=col3 THEN '2' 
             WHEN col2 != col1 and col2!=col3 THEN '1' 
        ELSE '0' END AS col2_values,

       CASE WHEN col3 = col1 and col3=col2 THEN '3' 
            WHEN col3 = col1 or col3=col2 THEN '2' 
            WHEN col3 != col1 and col3!=col2 THEN '1' 
       ELSE '0' END AS col3_values

FROM table_name

小提琴演示

于 2012-10-16T11:27:51.743 回答
0

假设表有一个键,你可以:

  1. 取消透视表。

  2. 将未透视的数据集连接回原始数据集。

  3. 对于原始列中的每一列,计数与未透视列的匹配项。

以下是上述实现的方法:

SELECT
  COUNT(t.col1 = s.col OR NULL) AS col1Values,
  COUNT(t.col2 = s.col OR NULL) AS col2Values,
  COUNT(t.col3 = s.col OR NULL) AS col3Values
FROM atable t
  INNER JOIN (
    SELECT
      t.id,
      CASE colind
        WHEN 1 THEN t.col1
        WHEN 2 THEN t.col2
        WHEN 3 THEN t.col3
      END AS col
    FROM atable t
    CROSS JOIN (SELECT 1 AS colind UNION ALL SELECT 2 UNION ALL SELECT 3) x
  ) s ON t.id = s.id
GROUP BY t.id
;

子查询使用交叉连接来取消透视表。该id列是关键列。此答案OR NULL中解释了该位。

于 2012-10-17T06:16:01.650 回答
0

我找到了一个不同的,非常简单的解决方案:-)

select if(col1=col1,1,0) + if(col2=col1,1,0) + if(col3=col1,1,0) as col1values -- col1 is needle
from table
于 2012-10-18T13:31:12.463 回答