1

以下查询检测到出现次数最多的diallednumber

SELECT COUNT( * ) AS  `Rows` , diallednumber
FROM logData
GROUP BY diallednumber
ORDER BY  `Rows` DESC 
LIMIT 20

我有另一列显示成本diallednumber

我无法编写查询以diallednumber根据发生的次数提供最昂贵的查询。

4

2 回答 2

2

每个号码的通话次数

SELECT COUNT(*) AS calls, dialledNumber
  FROM logData
 GROUP BY dialledNumber

最多呼叫一个号码

SELECT MAX(calls) AS maxCalls
  FROM (SELECT COUNT(*) AS calls, dialledNumber
          FROM logData
         GROUP BY dialledNumber
       ) AS c

呼叫次数最多的号码的呼叫费用总和

SELECT SUM(l.cost), l.dialledNumber
  FROM logData AS l
  JOIN (SELECT COUNT(*) AS calls, dialledNumber
          FROM logData
         GROUP BY dialledNumber
       ) AS c
    ON l.dialledNumber = c.dialledNumber
  JOIN (SELECT MAX(calls) AS maxCalls
          FROM (SELECT COUNT(*) AS calls, dialledNumber
                  FROM logData
                 GROUP BY dialledNumber
               )
       ) AS m
    ON m.maxCalls = c.calls

如果有两个号码的最大通话次数相同,则会显示两个号码。如果你想变得花哨,你可以用最大的成本总和来喝水。

m子查询可以在没有连接的情况下用作“简单”数字:

SELECT SUM(l.cost), l.dialledNumber
  FROM logData AS l
  JOIN (SELECT COUNT(*) AS calls, dialledNumber
          FROM logData
         GROUP BY dialledNumber
       ) AS c
    ON l.dialledNumber = c.dialledNumber
   AND c.calls = (SELECT MAX(calls) AS maxCalls
                    FROM (SELECT COUNT(*) AS calls, dialledNumber
                            FROM logData
                           GROUP BY dialledNumber
                         )
                 ) AS m

一个好的优化器会对两者使用相同的查询计划。

于 2013-01-09T16:55:03.230 回答
1

最大的成本:

SELECT diallednumber
     , COUNT(diallednumber)
     , SUM(cost) 
  FROM logdata 
 GROUP 
    BY diallednumber 
 ORDER 
    BY SUM(cost) DESC LIMIT 1;
于 2013-01-09T17:01:09.683 回答