根据总数限制sql查询和排名

时间:2012-11-01 16:22:44

标签: mysql

我有一个我的MYSQL数据库的SQL查询,并希望将结果限制为只有10个销售人员而不是20个。我已经尝试在查询中插入他们的名字,但一直收到错误。也可以根据总数进行排名。我正在使用的SQL查询是:

select sales_id, totalbuy, totalsell, totalbuy + totalsell as total from
(select sales_id, SUM(CASE WHEN side= 'buy' THEN 1 ELSE 0 END) AS totalbuy, 
SUM(CASE WHEN side= 'sell' THEN 1 ELSE 0 END) AS totalsell
from sales_id where sales_id='sales1', GROUP BY sales_id)q

它表示sales1我试图使用逗号和单引号添加剩余的9个sales_ids但无法使其工作。

1 个答案:

答案 0 :(得分:0)

如果您只想要某个sales_id,请使用“IN”子句。

如果您只想要前10名,请删除该行并使用LIMIT

select sales_id, totalbuy, totalsell, totalbuy + totalsell as total from
(select owner_id, SUM(CASE WHEN side= 'buy' THEN 1 ELSE 0 END) AS totalbuy, 
SUM(CASE WHEN side= 'sell' THEN 1 ELSE 0 END) AS totalsell
from sales_id  
where sales_id in ('sales1', 'sales2', 'sales3', 'sales4')-- if you wanna certain sales_id only
GROUP BY sales_id)q
order by total desc
limit 0, 10;--top 10 by total (bigger first)