我正在尝试从MySQL数据库中的表中获取前10种货币(及其请求数),并将所有其他货币分组为“其他”类别,请求数等于这些货币的请求数的总和
以下查询给出了正确的结果,但效率可能非常低。
SET @row_number = 0;
SELECT
rank,
CASE WHEN rank <=10 THEN ccy ELSE 'Other' END as ccy,
SUM(req_count) AS requests
FROM (SELECT CASE WHEN rank <= 10 THEN rank ELSE 11 END AS rank, ccy, req_count
FROM (SELECT (@row_number:=@row_number + 1) AS rank, ccy, req_count
FROM (SELECT have_currency AS ccy, COUNT(*) AS req_count
FROM db1.table1
GROUP BY have_currency
ORDER BY req_count DESC)
AS currencies)
AS currencies)
AS currencies
GROUP BY rank ASC;
结果:
# rank, ccy, requests
'1', 'SGD', '184481'
'2', 'USD', '10723'
'3', 'MYR', '8044'
'4', 'HKD', '7316'
'5', 'THB', '5725'
'6', 'JPY', '4930'
'7', 'INR', '2767'
'8', 'AUD', '2164'
'9', 'VND', '2130'
'10', 'CNY', '1965'
'11', 'Other', '10217'
有什么方法可以提高效率?
红利问题:是否可以返回请求计数的总数百分比而不是绝对数?
答案 0 :(得分:1)
这就是你要找的东西吗?
SELECT rank, IF(rank>10,'other',ccy) AS ccy,sum(req_count)
FROM (
SELECT @rank := (@rank := @rank+1) AS rank, ccy,req_count
FROM (
SELECT have_currency AS ccy, COUNT(*) AS req_count
FROM table1
GROUP BY have_currency
ORDER BY req_count DESC
) AS d1
) AS d2
CROSS JOIN (SELECT @rank := 0) AS param
GROUP BY LEAST(rank, 11);