6

我试图在多列中计数,然后按总和分组,其中相同的数据出现在任何列中

Source data table:

P1  P2  P3
-----------
a   b   
a   a   a
b   c   
a   b   b
b   a

我希望它显示如下内容:

Desired query output:

     Total
   -------------
a |    6
b |    5
c |    1
4

2 回答 2

7

您可以使用联合查询

SELECT x.f1,Count(x.f1) FROM
(SELECT p1 As F1 FROM table
 UNION ALL
 SELECT p2 As F1 FROM table
 UNION ALL
 SELECT p3 As F1 FROM table) x
GROUP BY x.f1
于 2012-09-10T14:53:40.863 回答
5

您可以union all在子查询和外部查询中记录count每个值。

SELECT b.a, COUNT(b.a)
FROM
    (
        SELECT P1 a
        FROM tableName
        UNION ALL
        SELECT P2 a
        FROM tableName
        UNION ALL
        SELECT P3 a
        FROM tableName
    ) b
GROUP BY b.a
于 2012-09-10T14:53:53.433 回答