按 ID 计算每列中的 ID
Count of ID in Each Column by ID
我有一个 table 这样的:
id | col1 | col2 | col3 |
-------------------------
1 | ab | ab | |
2 | bc | ab | cd |
3 | bc | cd | cd |
我想像这样生成每列中每个名字的计数:
name | col1 | col2 | col3 |
-------------------------
ab | 1 | 2 | 0 |
bc | 2 | 0 | 0 |
cd | 0 | 1 | 2 |
请注意,这只是一个示例,实际上有数千个名称,解决方案必须指定列,而不是名称。
这可能很简单,我试图搜索它但找不到任何正确的东西,可能是因为我不知道正确的术语。
我正在使用类似这样的方法来计算每个名称的总出现次数,但我不知道如何按列将其拆分出来:
这正在使用 MYSQL。
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
也许这行得通
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
希望这会有所帮助:
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
我有一个 table 这样的:
id | col1 | col2 | col3 |
-------------------------
1 | ab | ab | |
2 | bc | ab | cd |
3 | bc | cd | cd |
我想像这样生成每列中每个名字的计数:
name | col1 | col2 | col3 |
-------------------------
ab | 1 | 2 | 0 |
bc | 2 | 0 | 0 |
cd | 0 | 1 | 2 |
请注意,这只是一个示例,实际上有数千个名称,解决方案必须指定列,而不是名称。
这可能很简单,我试图搜索它但找不到任何正确的东西,可能是因为我不知道正确的术语。
我正在使用类似这样的方法来计算每个名称的总出现次数,但我不知道如何按列将其拆分出来:
这正在使用 MYSQL。
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
也许这行得通
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
希望这会有所帮助:
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