[英]Get a separate count for different values in same column
I want to have separate count for 3 possible values, ie onnet
, offnet
and international
in the same column ( type
) for each distinct user. 我想为每个不同的用户在同一列(
type
)中分别为3个可能的值(即onnet
, offnet
和international
计数。 My table is like this: 我的桌子是这样的:
number type
03212889438 onnet
03215350700 international
03212889438 offnet
03455919448 international
03215350700 onnet
03212889438 offnet
03455919448 offnet
So the sums would be: 因此总和为:
number onnet offnet international
03212889438 1 2 0
03215350700 1 0 1
03455919448 0 1 1
Then I want to display next to each number its type with the highest count: 然后,我想在每个数字旁边显示其计数最高的类型:
number highest
03212889438 Offnet
03215350700 Onnet
03455010448 Offnet
To get first result you will be required to use pivot table concept as below 为了获得首个结果,您将需要使用以下数据透视表概念
SELECT
number,
COUNT(CASE WHEN type = 'onnet' THEN id ELSE NULL END) AS onnet,
COUNT(CASE WHEN type = 'offnet' THEN id ELSE NULL END) AS offnet,
COUNT(CASE WHEN type = 'international' THEN id ELSE NULL END) AS international
FROM
test2
GROUP BY
number;
SELECT number,
CASE GREATEST(
count(type='onnet'),
count(type='offnet'),
count(type='international')
)
WHEN count(type='onnet') THEN 'onnet'
WHEN count(type='offnet') THEN 'offnet'
WHEN count(type='international') THEN 'international'
END AS highest
FROM test2
GROUP BY number;
above query will give you output as required 上面的查询将为您提供所需的输出
see sql fiddle 见SQL小提琴
You need to group your records using a suitable aggregate function; 您需要使用适当的汇总函数对记录进行分组 ; in MySQL one can do:
在MySQL中,可以做到:
SELECT number,
SUM(type='onnet') AS onnet,
SUM(type='offnet') AS offnet,
SUM(type='international') AS international
FROM my_table
GROUP BY number;
SELECT number,
CASE GREATEST(
SUM(type='onnet'),
SUM(type='offnet'),
SUM(type='international')
)
WHEN SUM(type='onnet') THEN 'onnet'
WHEN SUM(type='offnet') THEN 'offnet'
WHEN SUM(type='international') THEN 'international'
END AS highest
FROM my_table
GROUP BY number;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.