mysql - 选择给定日期每组的前 10 行

标签 mysql sql

我有一个这样的表:

id int primary key
user_id int, 
activity_date date, 
activity_type int, 
activity_value float

uniq 键(user_id、activity_date、activity_type)

我想获取给定日期 (activity_date)(例如今天或昨天)每个 activity_type 中按 activity_value 排序的前 10 行.

我尝试了自连接变体,但没有得到正确的结果。这是我尝试过的。

select 
  a.user_id, a.activity_date, a.activity_type, a.activity_value
from 
  my_table a
left join 
  my_table b on a.activity_type = b.activity_type and a.id < b.id
where 
  a.activity_date = curdate()
group by 
  a.id
having 
  count(*) < 10
order by 
  a.activity_value desc;

SQL fiddle :http://sqlfiddle.com/#!9/d30332/3

有人可以帮我纠正这个查询吗?

最佳答案

好吧,我想你已经差不多了,我想你只是错过了 b.activity_date = curdate() 条件。另外我认为LEFT JOIN是不必要的。

select a.*
from my_table a
join my_table b on a.activity_type = b.activity_type and 
                   a.activity_value <= b.activity_value
where a.activity_date = curdate() and b.activity_date = curdate()
group by a.id
having count(*) <= 10

demo

关于mysql - 选择给定日期每组的前 10 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46940149/

相关文章:

mysql - 在 Bluemix 应用程序上使用 Bluemix 的 SQL 数据库服务与 ClearDB MySQL 的优势

SQL 服务器 2008 R2 : Working with XML stored as BLOB (image data type)

mysql - SQL while 循环没有匹配任何条目

MySql - 限制查询的 SELECT 子句中允许的计算

mysql - 使用 MySQL 终端将 500mb csv 文件导入数据库

c# - 如何检查mysql中是否存在多个表?

SQL - 使用一个查询的结果作为一个语句中其他两个查询的基础

sql - 计算每天使用的不同 ID 数

mysql - 使用mysql慢速左连接

php - 不重复的多维数组