同时获取每列中每个值的计数

时间:2015-02-18 18:52:51

标签: mysql sql select count group-by

我试图看到类似的问题,但没有人帮助以有效的方式解决这个问题。

问题是我有一个包含这样的列的表:

table with 3 columns

我想计算每列中值的出现次数,但是对于表格的所有列,不仅要计算一次。

我想得到这样的东西:

p7     |  p7_count | p9 | p9_count
B      |   1       | A  |  2
A      |   1       | E  |  1
C      |   1      

但我只能使用单个查询来获取每个查询,例如:

SELECT p9, count(*) AS p9_Count
FROM respostas 
GROUP by p9
ORDER BY p9_Count DESC

但我得到的结果是:

p9 column occurrences count p9 column occurrences count

有没有办法为所有列执行此操作,而不必分别为每个列执行此操作并单独获取结果?

2 个答案:

答案 0 :(得分:1)

您可以使用union all执行此操作。有点不清楚到底你想要什么。也许这很接近:

select p, max(p7cnt) as p7cnt, max(p8cnt) as p8cnt, max(p9cnt) as p9cnt
from ((select p7 as p, count(*) as p7cnt, 0 as p8cnt, 0 as p9cnt
       from respostas
       group by p7
      ) union all
      (select p8, 0 as p7cnt, count(*) as p8cnt, 0 as p9cnt
       from respostas
       group by p8
      ) union all
      (select p9, 0 as p7cnt, 0 as p8cnt, count(*) as p9cnt
       from respostas
       group by p9
      )
     ) ppp
group by p;

答案 1 :(得分:1)

我认为这是你想象的那种。它变得有点乱,但你可以通过添加到coalesces来扩展它。为了使它与row_number函数(对于MySQL)一起工作,我已将其转换为使用子查询。当行数变大时,这甚至不会非常有效,因为SQL不适合这项工作。

select
    p1, p1_count, p2, p2_count, p3, p3_count
from
(
    select
        p1, p1_count,
        (
            select count(*) from
                (SELECT p1, count(*) AS p1_Count FROM respostas GROUP by p1) as t2
            where
                    t2.p1_Count <= t1.p1_Count
                or (t2.p1_Count  = t1.p1_Count and t2.p1 <= t1.p1)
        ) as rownum
    from (SELECT p1, count(*) AS p1_Count FROM respostas GROUP by p1) as t1
) as tt1

    full outer join

(
    select
        p2, p2_count,
        (
            select count(*) from
                (SELECT p2, count(*) AS p2_Count FROM respostas GROUP by p2) as t2
            where
                    t2.p2_Count <= t1.p2_Count
                or (t2.p2_Count  = t1.p2_Count and t2.p2 <= t1.p2)
        ) as rownum
    from (SELECT p2, count(*) AS p2_Count FROM respostas GROUP by p2) as t2
) as tt2
    on tt2.rownum = tt1.rownum

    full outer join

(
    select
        p3, p3_count,
        (
            select count(*) from
                (SELECT p3, count(*) AS p3_Count FROM respostas GROUP by p3) as t2
            where
                    t2.p3_Count <= t1.p3_Count
                or (t2.p3_Count  = t1.p3_Count and t2.p3 <= t1.p3)
        ) rownum
    from (SELECT p3, count(*) AS p3_Count FROM respostas GROUP by p2) as t3
) as tt3
    on tt3.rownum = coalesce(tt1.rownum, tt2.rownum)

order by
    coalesce(tt1.rownum, tt2.rownum, tt3.rownum)