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