gpt4 book ai didi

mysql - 使用日期对组使用子查询计算索引位置

转载 作者:行者123 更新时间:2023-11-30 22:53:27 25 4
gpt4 key购买 nike

select user_id as sponsor_id,sum(points),created_at 
from points_history
where created_at between '2014/08/12' and '2015/08/12' and transaction_type="debit"
group by user_id,DATE_FORMAT(created_at,"%d %M %Y")
order by DATE_FORMAT(created_at,"%d %M %Y"),sum(points) desc



sponsor_id sum(points) created_at
1 30 2014-12-08 10:54:59
2 25 2014-12-09 05:43:11
3 20 2014-12-09 06:58:40
1 5 2014-12-09 05:56:12
1 34 2014-08-23 10:42:32

这里我想每天使用 sponsor_id 计算特定赞助商的排名。我想构建一个可以返回如下所示内容的查询:

sponsor_id      rank    created_at      
1 1 2014-12-08 10:54:59
1 3 2014-12-09 05:56:12
1 1 2014-08-23 10:42:32

我想我可以像这样使用子查询

select * 
from (select user_id as sponsor_id,sum(points),created_at
from points_history
where created_at between '2014/08/12' and '2015/08/12' and transaction_type="debit"
group by user_id,DATE_FORMAT(created_at,"%d %M %Y")
order by DATE_FORMAT(created_at,"%d %M %Y"),sum(points) desc
) as t
where t.sponsor_id = 1

但是这里如何计算排名。

最佳答案

试试这个:

SELECT sponsor_id, points, created_at, 
IF(@dte=@dte:=DATE(created_at), @rank:=@rank+1, @rank:=1) AS rank
FROM (SELECT user_id AS sponsor_id, SUM(points) points, created_at
FROM points_history
WHERE created_at BETWEEN '2014-08-12' AND '2015-08-12' AND
transaction_type = "debit"
GROUP BY user_id, DATE_FORMAT(created_at,"%d %M %Y")
ORDER BY DATE(created_at), SUM(points) DESC
) AS A, (SELECT @rank:=0, @dte:='') AS B
ORDER BY DATE(created_at), points DESC;

关于mysql - 使用日期对组使用子查询计算索引位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27373691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com