[英]Get a count of each value from every column at the same time
我試圖看到類似的問題,但是沒有一個人在幫助解決這種有效的方法。
事情是我有一個帶有這樣的列的表:
我想計算表中每一列中值的出現次數,而不僅僅是表中的所有列。
我想得到這樣的東西:
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
但是我得到的結果是:
有沒有一種方法可以對所有列執行此操作,而不必分別為每個列執行操作並分別獲取結果?
您可以通過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;
我認為這是您所描繪的那種東西。 它有點混亂,但是您可以通過添加合並來擴展它。 為了使其與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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.