以下查询检测到出现次数最多的diallednumber
:
SELECT COUNT( * ) AS `Rows` , diallednumber
FROM logData
GROUP BY diallednumber
ORDER BY `Rows` DESC
LIMIT 20
我有另一列显示成本diallednumber
。
我无法编写查询以diallednumber
根据发生的次数提供最昂贵的查询。
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
一个好的优化器会对两者使用相同的查询计划。
最大的成本:
SELECT diallednumber
, COUNT(diallednumber)
, SUM(cost)
FROM logdata
GROUP
BY diallednumber
ORDER
BY SUM(cost) DESC LIMIT 1;