我的mysql数据库上有这个表:
date | client | total
2015-01-01 | john | 85.00
2015-01-01 | alfred | 35.00
2015-01-01 | georgy | 125.00
2015-01-01 | linda | 42.00
2015-01-01 | alex | 76.00
2015-01-01 | john | 94.00
2015-01-01 | john | 75.30
我想按客户名称分组计算总金额和百分比,所以我提出了这个问题:
SELECT client, total, round(total*100/t.th,1) as percent
FROM (
SELECT client, sum(total) as total
FROM mytable
WHERE date='2015-01-01'
GROUP BY `client`) c
JOIN ( select sum(total) as th from mytable
WHERE date='2015-01-01') t
order by percent desc
它运作良好,但现在我只想列出3个第一个结果,所以我在最后添加了LIMIT 3
但是它不起作用,它仍然显示了相同数量的结果。
更新
当我执行此查询时,我获得:
client | total | percent
john | 254.3 | 47.8
georgy | 125 | 23.5
alex | 76 | 14.3
linda | 42 | 7.9
alfred | 35 | 6.6
直到这里是正确的,但现在我只想要3个第一行,所以我修改:
SELECT client, total, round(total*100/t.th,1) as percent
FROM (
SELECT client, sum(total) as total
FROM mytable
WHERE date='2015-01-01'
GROUP BY `client`) c
JOIN ( select sum(total) as th from mytable
WHERE date='2015-01-01') t
order by percent desc LIMIT 3
但它不起作用,它仍然显示相同的结果,我想要这个:
client | total | percent
john | 254.3 | 47.8
georgy | 125 | 23.5
alex | 76 | 14.3
我该如何解决?
答案 0 :(得分:2)
尝试以下查询,在变量中存储特定日期的行数,以便您不需要交叉加入:
select @rows := sum(total) from myTable where date = '2015-01-01';
SELECT client, total, round(total*100/@rows,1) as percent
FROM (
SELECT client, sum(total) as total
FROM mytable
WHERE date='2015-01-01'
GROUP BY `client`
)
order by percent desc
LIMIT 3;
或者,您可以执行以下操作,而不是编写2个不同的查询:
SELECT client, total, round(total*100/total_sum,1) as percent
FROM (
SELECT client, @total_sum:= @total_sum + sum(total) as total_sum, sum(total) as total
FROM mytable
WHERE date='2015-01-01'
GROUP BY `client`
), (select @total_sum:=0) as t
order by percent desc
LIMIT 3;