这是我的查询,我得到了前15名的结果,一切都没问题,但前15名下面有很多行,我需要收集那些 结果,计算它们并在同一查询中将其命名为“其他”。以下是我得到的结果和查询:
SELECT `Person` , COUNT( `Person` ) AS Total
FROM taxes
WHERE `Person` IS NOT NULL
AND `Person` <> ''
AND `Date`
BETWEEN '2013-11-11'
AND '2013-11-30'
GROUP BY (
`Person`
)
ORDER BY `Total` DESC
LIMIT 5
结果
Person - Total
a ------ 66
b ------ 44
c ------ 33
d ------ 13
e ------ 14
-----------
f ------ 10
g ------ 8
h ------ 7
以下是我想要的内容:
Person | Total
a ------ 66
b ------ 44
c ------ 33
d ------ 13
e ------ 14
-----------
others --- 25
谢谢!
答案 0 :(得分:0)
使用联盟,限制和抵消
SQLFiddle: http://sqlfiddle.com/#!2/69e65/1
(SELECT `Person` ,
COUNT(`Person`) AS `Total`
FROM taxes
WHERE `Person` IS NOT NULL
AND `Person` <> ''
AND `Date` BETWEEN '2013-11-11' AND '2015-11-30'
GROUP BY `Person`
ORDER BY COUNT(`Person`) DESC LIMIT 2)
UNION
(SELECT 'Other',
sum(`Total`) AS `Total`
FROM
( SELECT `Person` ,
COUNT(`Person`) AS Total
FROM taxes
WHERE `Person` IS NOT NULL
AND `Person` <> ''
AND `Date` BETWEEN '2013-11-11' AND '2015-11-30'
GROUP BY `Person`
ORDER BY COUNT(`Person`) DESC
LIMIT 2, 18446744073709551615) AS TEMP
);
使用@row变量
SQLFiddle: http://sqlfiddle.com/#!2/0a61a/5
set @row:=1;
select if(@row>2, 'Other', `Person`) as `Person`,
sum(`Total`) as `Total`,
@row:=@row+1 as `IgnoreColumn`
from
(
SELECT `Person` ,
COUNT(`Person`) AS Total
FROM taxes
WHERE `Person` IS NOT NULL
AND `Person` <> ''
AND `Date` BETWEEN '2013-11-11' AND '2015-11-30'
GROUP BY `Person`
ORDER BY COUNT(`Person`) DESC
) as TEMP
group by if(@row>2, 'Other', `Person`)
order by @row;