获取同一列中不同值的单独计数

时间:2013-05-08 08:43:05

标签: php mysql

我想对3个可能的值进行单独计数,即每个不同用户的同一列(onnet)中的offnetinternationaltype。我的桌子是这样的:

number      type
03212889438 onnet
03215350700 international
03212889438 offnet
03455919448 international
03215350700 onnet
03212889438 offnet
03455919448 offnet

所以总和将是:

number      onnet   offnet  international
03212889438 1       2       0
03215350700 1       0       1
03455919448 0       1       1

然后我想在每个数字旁边显示其最高计数类型:

number      highest
03212889438 Offnet
03215350700 Onnet
03455010448 Offnet

2 个答案:

答案 0 :(得分:1)

要获得第一个结果,您需要使用数据透视表概念,如下所示

    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;

上面的查询将根据需要提供输出

请参阅sql fiddle

答案 1 :(得分:1)

您需要使用合适的聚合函数分组您的记录;在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;

sqlfiddle上查看。