-1

我想为每个不同的用户分别计算 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
4

2 回答 2

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 小提琴

于 2013-05-08T08:49:56.430 回答
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上查看。

于 2013-05-08T08:53:23.193 回答