计算不同的值多个col

问题描述 投票:1回答:1

我有这个表(模型 - 不是SQL中的表,所有键都连接到一个真实的表,但我需要计算此模型中存在的键。)

key1   key2  key 3
v1     d1    t1
v2     d2    t1
v3     d1    t4
v1     d3    t8
v1     d2    t4

结果需要返回

key1 v1 3
key1 v2 1
key1 v3 1
key2 d1 2

小提琴测试http://sqlfiddle.com/#!9/c102f

我无法逐个选择所有键,因为键数= 79,行数= 1 115 260

逐个选择过程需要2分钟

mysql count distinct
1个回答
1
投票

您不能在单个select语句中对单独的列进行分组,因为第一个组会影响第二个等。

除了逐个选择它们之外别无他法,但是如果你只想要将所有内容都集成到一个结果中,你可以使用union

(select 'key1' AS column_origin, key1, count(key1) from TestTable group by key1)
union all
(select 'key2', key2, count(key2) from TestTable group by key2)
union all
(select 'key3', key3, count(key3) from TestTable group by key3);
© www.soinside.com 2019 - 2024. All rights reserved.