我有一個學生表(ID,分數,部門)和部門表(ID,名字)。我試圖在查詢中添加某些條件。
School_dept
--------- -------------
| dept_id | name |
--------- -------------
| 1 | Admin |
--------- -------------
| 2 | 化學 |
--------- -------------
| 3 | 物理 |
--------- -------------
| 4 | Biology |
--------- -------------
| 5 | Mathematics |
--------- -------------
學生
------------ ------- <
| student_id | score | departments |
------------ ------- ------------
| 26 | 11 | 4 |
------------ ------- ------------
| 34 | 11 | 3 |
------------ ------- ------------
| 76 | 11 | 2 |
------------ ------- ------------
| 49 | 11 | 1 |
------------ ------- ------------
| 38 | 11 | 5 |
------------ ------- ------------
- 選擇所有學生人數少于5人的學校部門 。
- 按學生的總分從高到低排序學校部門。如果存在平局,那么學生人數最多的部門將排在第一位;如果仍然存在平局,那么最小的部門_id應該排在第一位。
- 只考慮奇數行,不包括偶數行 。
我的嘗試
SELECT * FROM (
SELECT * , ROW_NUMBER() OVER() AS ROW_ID FROM (
SELECT dept_id, name, count(E. student_id) as total_students, SUM(score) as total_score
from Students E
LEFT JOIN school_dept D on dept_id=student_id
group by 1, 2
) as O
WHERE total_students<3
order by total_score desc, total_students desc, dept_id asc
) as U
WHERE ROW_ID %2 <>/span>0
預期輸出是
name, total_students, total_score
admin,1,11
物理1,11,11。
數學,1,11。
http://sqlfiddle.com/#!17/248eb8/2
uj5u.com熱心網友回復:
我認為你的查詢中有一個連接問題(將student_id與dept_id連接起來),你正在選擇少于三個學生(但要求說少于五個學生)。
請嘗試以下方法:
select department as "name", total_students, total_score
來自的
(
select *, row_number() over (order by total_score desc, total_students desc, dept_id) row_id
來自的
(
select sum( score) total_score, count(student_id) total_students, sd.name department, sd.dept_id
from students s
join school_dept sd on s.department = sd.dept_id
group by 3, 4
having count(student_id) </span> 5
)t
) tt
where row_id%2 <> 0
請看SQL Fiddle 這里。
uj5u.com熱心網友回復:
由于School_dept是部門的父表,所以JOINING將School_dept左接Students。因為一個部門可能沒有學生,所以左聯是最完美的。但是如果考慮到那些有學生的部門,那么就使用INNER JOIN。
--SQL SERVER (v2017)
SELECT p.dept_name "Name", p.total_students, p.total_score
FROM (SELECT *)
, ROW_NUMBER() OVER (ORDER BY T. total_score DESC, t.total_students DESC, t.dept_id) row_num
FROM (SELECT sd.dept_id
, MAX(sd.name) dept_name
, COUNT(s.student_id) total_students
, SUM(s.score) total_score
FROM School_dept sd
LEFT JOIN 學生s
ON sd.dept_id = s.department
GROUP BY sd.dept_id
HAVING COUNT(s.student_id) < 5) t) p
WHERE (p.row_num % 2) ! = 0;
請從網址https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=abf4b40f692d085b98054aa9c9a1dcc7
uj5u.com熱心網友回復:
我認為下面的查詢應該可以作業
select *,
Rank() over (order by Score desc, TotalStudent desc,dept_id asc) as Serial
來自的
(
select d.dept_id,d.Name,COUNT(student_id) TotalStudent,sum(Score) Score
來自學生s
left join School_dept d on s.department=d.dept_id
where d.dept_id % 2 <>/span> 0
group by d.Name,d.dept_id
) a where TotalStudent </span> 5
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/310870.html
標籤:
上一篇:PHP關聯陣列計數和提取
