我想運行一個 SQL 查詢來計算串列中的通過次數和失敗次數。我創建了一個包含學生和成績的場景,以更好地解釋我的問題。
我有兩張桌子,一張是學生桌
| 學生卡 | 名 | 姓 |
|---|---|---|
| 1 | 海綿 | 鮑勃 |
| 2 | 帕特里克 | 星星 |
另一個表是成績
| 學生卡 | 主題 | 分數 | 地位 |
|---|---|---|---|
| 1 | 數學 | 70 | 經過 |
| 1 | 英語 | 70 | 經過 |
| 1 | 科學 | 60 | 失敗 |
| 2 | 數學 | 75 | 經過 |
| 2 | 英語 | 80 | 經過 |
| 2 | 科學 | 75 | 經過 |
| 3 | 數學 | 70 | 經過 |
| 3 | 英語 | 80 | 經過 |
| 3 | 科學 | 75 | 經過 |
一些規則 要獲得汽車執照,您需要通過數學和英語。要獲得船執照,您需要通過數學英語和科學。
我將如何計算可以獲得汽車和船駕照的學生總數?
獲得如下輸出
| 汽車牌照數量 | 3 |
| NB船牌數量 | 2 |
我添加了一個 SQLFiddle 以獲取更多資訊。
http://sqlfiddle.com/#!18/900a7
uj5u.com熱心網友回復:
您可以使用 UNION 將兩種許可證型別的計數合并在一起來實作此目的
SELECT 'Car' AS LicenceType,
COUNT(*) AS NumStudents
FROM (
SELECT StudentId
FROM grades
WHERE (subject = 'Maths' AND status = 'pass') OR
(subject = 'English' AND status = 'pass')
GROUP BY StudentId
HAVING COUNT(*) = 2
) Car
UNION ALL
SELECT 'Boat' AS LicenceType,
COUNT(*) AS NumStudents
FROM (
SELECT StudentId
FROM grades
WHERE (subject = 'Maths' AND status = 'pass') OR
(subject = 'English' AND status = 'pass') OR
(subject = 'Science' AND status = 'pass')
GROUP BY StudentId
HAVING COUNT(*) = 3
) Boat
順便說一句,您的 SQL 小提琴與您問題中的資料表不匹配 - 學生 3 具有不同的通過/失敗資料
uj5u.com熱心網友回復:
需要使用 COUNT 來跟蹤滿足的要求,并查看每個學生是否滿足所有要求。然后將結果聚合到您想要的結果集中(您想要的結果集值似乎與您的示例資料不匹配)
SELECT A.StudentID
,CarLicenseRequirementsMet = CASE WHEN COUNT(CASE WHEN B.[Subject] IN ('MATHS','ENGLISH') THEN 1 END) = 2/*Both requirements met*/ THEN 'Y' END
,BoatLicenseRequirementsMet = CASE WHEN COUNT(CASE WHEN B.[Subject] IN ('MATHS','ENGLISH','SCIENCE') THEN 1 END) = 3 /*All 3 requirements met*/ THEN 'Y' END
INTO #StudentRequirement
FROM student AS A
INNER JOIN grades AS B
ON A.StudentID = B.StudentID
WHERE B.[Status] = 'Pass'
GROUP BY A.StudentID
/*Returned for reference only*/
SELECT * FROM #StudentRequirement
/*Aggregated results*/
SELECT 'Number of Car Licenses',COUNT(*) FROM #StudentRequirement WHERE CarLicenseRequirementsMet = 'Y'
UNION ALL
SELECT 'Number of Boat Licenses',COUNT(*) FROM #StudentRequirement WHERE BoatLicenseRequirementsMet = 'Y'
uj5u.com熱心網友回復:
您可以使用視窗函式計算 CTE 中符合條件的學生,然后匯總結果:
with t as (
select studentId,
Sum(case when subject in ('maths','english') then 1 end) over(partition by studentid) Car,
Sum(case when subject in ('maths','english', 'science') then 1 end) over(partition by studentid) Boat
from grades
where status='pass'
)
select distinct 'Number of Car Licenses', Sum(Count(distinct car)) over()
from t
where car=2
group by studentid
union all
select distinct 'Number of Boat Licenses', Sum(Count(distinct Boat)) over()
from t
where boat=3
group by studentid
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/407953.html
標籤:
下一篇:使用條件匹配來自不同表的2列
