【问题标题】:select the last record in each group along with count选择每组中的最后一条记录以及计数
【发布时间】:2016-06-16 07:31:58
【问题描述】:

我们有一个名为“atable”的以下 sqlite3 表

id  student assignment      grade
-----------------------------------
1    A       123             9
2    A       456             9
3    A       234             8
4    B       534             7
5    B       654             9
6    C       322             7

id 是唯一的,并且对于每条记录都会递增。我们正在通过运行查询获取每个用户的最新分配

SELECT student, assignment, grade from atable where id in 
       (select max(id) from atable group by student) order by id desc

这工作正常。但是,我们还需要获取每个用户在同一查询中获得特定成绩的作业数量,比如 9。

任何想法建议如何增强或重写上述查询以返回计数。如前所述,我们使用的是 sqlite3。

谢谢

【问题讨论】:

  • 想要的结果是什么样的?

标签: mysql sql sqlite


【解决方案1】:

您可以使用此相关查询:

SELECT t.student, t.assignment, t.grade, 
       (SELECT COUNT(*) FROM atable s
        WHERE s.student = t.student and s.grade >= 9) as total_above_9
from atable t
where t.id in 
   (select max(id) from atable group by student)
order by t.id desc

【讨论】:

  • 谢谢,帮了大忙。
  • @saggi : 在 t.grade 之后需要添加逗号,如 (t.grade,(select)...) 否则不执行查询。所以请更新您的查询
【解决方案2】:

最好加入包含原始表的聚合版本的派生表:

select t1.student, t1.assignment, t1.grade, t2.cnt 
from mytable as t1
join (
   select student, max(id) as id, 
          count(case when grade = 9 then 1 end) as cnt
   from mytable 
   group by student
) as t2 on t1.id = t2.id

【讨论】:

  • 谢谢 Glogos,我也试试这个。
【解决方案3】:

试试这个;)

select t1.student, t1.assignment, t1.grade, t2.count
from atable t1
inner join (select max(id) as id, count(if(grade=9, 1, null)) as count from atable group by student) t2
on t1.id = t2.id
order by t1.id desc

【讨论】:

  • 感谢 Reno,但 sqlite 不支持 'if'。
猜你喜欢
  • 2013-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-24
相关资源
最近更新 更多