[英]how to use the result of 2 columns to create calculated column in Oracle sql
我與 oracle sql 堆疊我有 4 列課程,性別,總注冊,總通過(最后 2 列是計算出來的,在數據庫中不存在)
我正在嘗試創建第 5 列來計算 (Total Pass / Total Enrolled) *100 的結果我使用了以下 sql
select Course , Gender",
Count( case
when Grade In('A+','A-','B','B+','B-','C','C+''F') then 'Total Enrolled with grades’
end ) as "Total_Enrolled",
Count ( case
when Grade In ('A+','A-','B','B+','B-','C','C+') then 'Pass'
end ) as "Total_Pass"
from Result
group by
Course,
Gender
order by Course
感謝你的幫助
謝謝
嗯。 . . 這聽起來像條件聚合:
select Course, Gender,
sum(case when Grade In ('A+', 'A-', 'B', 'B+', 'B-', 'C', 'C+', 'F')
then 1 else 0
end) as Total_Enrolled
sum(case when Grade In ('A+', 'A-', 'B', 'B+', 'B-', 'C', 'C+')
then 1 else 0
end) as Total_Passed,
( sum(case when Grade In ('A+', 'A-', 'B', 'B+', 'B-', 'C', 'C+')
then 1 else 0
end) /
sum(case when Grade In ('A+', 'A-', 'B', 'B+', 'B-', 'C', 'C+', 'F')
then 1
end)
) as pass_ratio
from Result
group by Course, Gender
order by Course;
如果您可以在WHERE
子句中進行過濾,這將大大簡化:
select Course, Gender,
count(*) as Total_Enrolled
sum(case when Grade In ('A+', 'A-', 'B', 'B+', 'B-', 'C', 'C+')
then 1 else 0
end) as Total_Passed,
avg(case when Grade In ('A+', 'A-', 'B', 'B+', 'B-', 'C', 'C+')
then 1
end) as pass_ratio
from Result
where Grade In ('A+', 'A-', 'B', 'B+', 'B-', 'C', 'C+', 'F')
group by Course, Gender
order by Course;
一個簡單的選擇是將當前查詢用作 CTE,然后重用其計算列來獲得最終結果:
WITH
temp
AS
( SELECT course,
gender,
COUNT (CASE
WHEN grade IN ('A+',
'A-',
'B',
'B+',
'B-',
'C',
'C+',
'F')
THEN
'Total Enrolled with grades'
END) AS total_enrolled,
COUNT (CASE
WHEN grade IN ('A+',
'A-',
'B',
'B+',
'B-',
'C',
'C+')
THEN
'Pass'
END) AS total_pass
FROM result
GROUP BY course, gender)
SELECT course,
gender,
total_enrolled,
total_pass,
--
(total_pass / total_enrolled) * 100 AS fifth_column
FROM temp
ORDER BY course
或者,您可以重新輸入這些CASE
並在同一個查詢中執行,但這有點難以閱讀。
順便說一句,就像他們在2001 年所說的:太空漫游:“到處都是星星”。 您的代碼充滿了錯誤。 在這里發布內容時應該更加小心。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.