[英]select the last record in each group along with count
我們有一個名為“ 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。
謝謝
您可以使用以下相關查詢:
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
最好加入包含原始表的聚合版本的派生表:
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
嘗試這個;)
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.