从MYSQL中的列作为行获取表中的数据

时间:2013-01-13 19:13:09

标签: mysql sql pivot aggregate-functions

任何人都可以帮我查询将列转换为行然后相应地查找数据。

问题如下。我已经尝试了一个查询,将列名称变为行,但我无法获取值或有任何想法为列3和列4弄清楚。我是SQL中的新bibe。有人可以帮我从这里出去吗。我从朋友那里听到建议使用枢轴,当我浏览时发现MYSQL不支持PIVOT

Input Table: 

E1           E2           E3           E4           E5           E6

Null         1234         234          12           A            B
123          Null         Null         Null         12           B
Null         Null         Null         Null         Null         Null
123          2            1            A            1            2


Output Table:

C1           C2           Count           TotalC           percent           

E1           123          2               2                1
E2           1234         1               2                0.5
E2           2            1               2                0.5
E3           234          1               2                0.5
E3           1            1               2                0.5
E4           12           1               2                0.5
E4           A            1               2                0.5
E5           A            1               3                0.3
E5           12           1               3                0.3
E5           1            1               3                0.3
E6           B            2               3                0.6
E6           2            1               3                0.3

问题的解释:

  1. C1是输入表的列名。
  2. C2是这些列中的数据。
  3. Count是每列中类似项目和单打的数量。
  4. TotalC是总非空值的数量。
  5. 百分比是count / totalc。
  6. 我工作的查询:SELECT (COLUMN_NAME)AS Column1 FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'inputtable';

    注意:在MYSQL中查询。

1 个答案:

答案 0 :(得分:1)

正如我在上面的评论中所提到的,你应该以不同的方式处理这个问题。见What is the XY problem?

但是,如果必须,您可以使用UNION解决此问题:

SELECT *, Count/TotalC AS percent
FROM (
  SELECT   'E1' AS C1, E1 AS C2, COUNT(*) AS Count
  FROM     Input
  WHERE    E1 IS NOT NULL
  GROUP BY C2
UNION ALL
  SELECT   'E2' AS C1, E2 AS C2, COUNT(*) AS Count
  FROM     Input
  WHERE    E2 IS NOT NULL
  GROUP BY C2
UNION ALL
  SELECT   'E3' AS C1, E3 AS C2, COUNT(*) AS Count
  FROM     Input
  WHERE    E3 IS NOT NULL
  GROUP BY C2
UNION ALL
  SELECT   'E4' AS C1, E4 AS C2, COUNT(*) AS Count
  FROM     Input
  WHERE    E4 IS NOT NULL
  GROUP BY C2
UNION ALL
  SELECT   'E5' AS C1, E5 AS C2, COUNT(*) AS Count
  FROM     Input
  WHERE    E5 IS NOT NULL
  GROUP BY C2
UNION ALL
  SELECT   'E6' AS C1, E6 AS C2, COUNT(*) AS Count
  FROM     Input
  WHERE    E6 IS NOT NULL
  GROUP BY C2
) t1 NATURAL JOIN (
  SELECT 'E1' AS C1, COUNT(E1) AS TotalC FROM Input
UNION ALL
  SELECT 'E2' AS C1, COUNT(E2) AS TotalC FROM Input
UNION ALL
  SELECT 'E3' AS C1, COUNT(E3) AS TotalC FROM Input
UNION ALL
  SELECT 'E4' AS C1, COUNT(E4) AS TotalC FROM Input
UNION ALL
  SELECT 'E5' AS C1, COUNT(E5) AS TotalC FROM Input
UNION ALL
  SELECT 'E6' AS C1, COUNT(E6) AS TotalC FROM Input
) t2

sqlfiddle上查看。