【问题标题】:Calculate index position using sub queries on group by using date使用日期在组上使用子查询计算索引位置
【发布时间】:2014-12-09 07:40:42
【问题描述】:
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

在这里,我想每天使用赞助商 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

但是如何在这里计算排名。

【问题讨论】:

  • 最高分将定义排名,更多积分将获得最高排名

标签: mysql sql select sql-order-by ranking


【解决方案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;

【讨论】:

  • 谢谢,它的工作。我必须把它放在另一个子查询中来计算按日期分组的特定用户的排名。
猜你喜欢
  • 1970-01-01
  • 2020-07-25
  • 1970-01-01
  • 2021-10-18
  • 2022-01-08
  • 2013-10-14
  • 2011-07-18
  • 2011-11-29
  • 2018-07-03
相关资源
最近更新 更多