我不确定该问题究竟是什么标题
我在表格中有以下列
id, slug, date, market
每一行都是日期,硬币名称和市值。
我按日期分组
SELECT slug, date, market
from coin
order by date asc, market desc
slug date market
bitcoin 2013-04-28 1500520000
litecoin 2013-04-28 73773400
peercoin 2013-04-28 7255800
namecoin 2013-04-28 5969080
terracoin 2013-04-28 1510150
novacoin 2013-04-28 1155160
bitcoin 2013-04-29 1491160000 -- new date
litecoin 2013-04-29 74952700
peercoin 2013-04-29 7262850
namecoin 2013-04-29 5977460
terracoin 2013-04-29 1508860
novacoin 2013-04-29 1162460
bitcoin 2013-04-30 1597780000 -- new date
litecoin 2013-04-30 75726800
peercoin 2013-04-30 7641700
namecoin 2013-04-30 7185910
terracoin 2013-04-30 1650870
novacoin 2013-04-30 1249450
bitcoin 2013-05-01 1542820000 -- new date
litecoin 2013-05-01 73901200
我想为每个日期添加市场,但我只希望按市场每日包含前3行。最终,我希望数据看起来像这样
date total market
29/04/2013 1573375550 -- (1500520000 + 73773400 + 7255800)
30/04/2013 1681148500
01/05/2013 1616721200
感谢任何帮助。感谢
答案 0 :(得分:1)
我认为变量是枚举过滤行的最简单方法:
select date, sum(market)
from (select c.*,
(@rn := if(@d = date, @rn + 1,
if(@d := date, 1, 1)
)
) as rn
from coin c cross join
(select @d := '', @rn := 0) params
order by date, market desc
) c
where rn <= 3
group by date;
评论:
row_number()
代替变量。date, market desc
进行排序。答案 1 :(得分:0)
您的云按日期使用组并限制为3(然后还原结果以获得显示的结果)
select * from (
select date, sum(market)
from your_table
group by date
order by date desc limit 3
) t
order by t.date asc