I have a table like this:
id | col1 | col2 | col3 |
-------------------------
1 | ab | ab | |
2 | bc | ab | cd |
3 | bc | cd | cd |
And i want to produce the count of each of the names in each column like this:
name | col1 | col2 | col3 |
-------------------------
ab | 1 | 2 | 0 |
bc | 2 | 0 | 0 |
cd | 0 | 1 | 2 |
Note that this is just an example, in reality there are 1000s of names, the solution will have to specify the columns, but not the names.
This is probably very simple, and I tried to search for it but couldn't find anything quite right, likely because i didn't know the right term.
I was using something like this to count the total occurrences of each name, but I can't figure out how to split it back out by column: Selecting distinct records from multiple column of a table with their count
This is using MYSQL.
答案 0 :(得分:1)
select name, sum(cnt1), sum(cnt2), sum(cnt3)
from
(
select col1 as name, count(*) as cnt1 , null as cnt2 , null as cnt3 from t group by col1
union all
select col2, null, count(*), null from t group by col2
union all
select col3, null, null, count(*) from t group by col3
) as dt
答案 1 :(得分:0)
perhaps this would work
select colcounts.col, sum(colcounts.cnt) from
(
(select col1 as col, count(*) as cnt from TableLikeThis group by col1)
union
(select col2 as col, count(*) as cnt from TableLikeThis group by col2)
union
(select col3 as col, count(*) as cnt from TableLikeThis group by col3)
) as colcounts
group by col
答案 2 :(得分:0)
希望这会有所帮助:
select name ,sum(s1), sum(s2), sum(s3)
from
(
select cnt1 as name , count(cnt1) as s1, count(if(cnt2=cnt1,1,0)) as s2, count(if(cnt3=cnt1,1,0)) as s3
from your_table group by cnt1
union all
select cnt2 as name , count(if(cnt1=cnt2,1,0)) as s1, count(cnt2) as s2, count(if(cnt3=cnt2,1,0)) as s3
from your_table group by cnt2
union all
select cnt3 as name , count(if(cnt1=cnt3,1,0)) as s1, count(if(cnt2=cnt3,1,0)) as s2, count(cnt3) as s3
from your_table group by cnt3
)
group by name