我有一个包含2列X,Y的表。我想计算两列中每条记录的出现次数。 例如:
X | Y
A | A
B | A
B | C
D | C
结果应为
variable | X_count | Y_count
A | 1 | 2
B | 2 | 0
C | 0 | 2
D | 1 | 0
如何在mysql中实现这一目标?
编辑:好的,花了几个小时后,我确保Y中的所有值都是X的子集。即对于任何变量,X_count永远不会为0。这有助于优化吗?
答案 0 :(得分:0)
我认为你需要一个工会临时表和分组
select v.variable, a.count(*), b.count(*)
from
(select x as variable
from my_table
union select y
from my_table ) as v
inner join my_table as a on a.X = v.variable
inner join my_table as b on b.y = v.variable
group by v.variable
事实上Y是X的一个子集允许避免联合然后但是无论如何我们需要不同的X
select v.variable, a.count(*), b.count(*)
from
(select distinct x as variable
from my_table ) as v
inner join my_table as a on a.X = v.variable
inner join my_table as b on b.y = v.variable
group by v.variable