我怎样才能重复使用avg(examinee_grade_science + ...)
?
如您所见,我在CASE
表达式下重复了它。我可以将它分配给变量并在CASE
表达式中使用它吗?
我尝试使用SET (set @ave_grade = examine_grade...)
,但它不起作用。
无论如何它有可能吗?
select
examinee_grade_science as "Science Grade",
examinee_grade_math as "Math Grade",
examinee_grade_literature as "Literature Grade",
examinee_grade_science + examinee_grade_math + examinee_grade_literature as "TOTAL",
avg(examinee_grade_science + examinee_grade_math + examinee_grade_literature) as "AVERAGE",
case when avg(examinee_grade_science + examinee_grade_math + examinee_grade_literature) < 93
then 'PASSED'
else 'FAILED'
end as "REMARKS"
from examinee
答案 0 :(得分:3)
使用子查询计算平均值,然后使用分配给外部查询中的平均计算值的别名来检查通过/失败
SELECT *,
case when AVERAGE < 93
then 'PASSED'
else 'FAILED'
end as "REMARKS"
FROM
(
select
examinee_grade_science as "Science Grade",
examinee_grade_math as "Math Grade",
examinee_grade_literature as "Literature Grade",
examinee_grade_science + examinee_grade_math + examinee_grade_literature as "TOTAL",
avg(examinee_grade_science + examinee_grade_math + examinee_grade_literature) as "AVERAGE"
from examinee
) t
答案 1 :(得分:2)
我会使用CROSS APPLY
为表达式创建别名:
select
examinee_grade_science as "Science Grade",
examinee_grade_math as "Math Grade",
examinee_grade_literature as "Literature Grade",
grade_sum as "TOTAL",
avg(grade_sum) as "AVERAGE",
case when avg(grade_sum) < 93
then 'PASSED'
else 'FAILED'
end as "REMARKS"
from
examinee
CROSS APPLY
(
SELECT
examinee_grade_science + examinee_grade_math + examinee_grade_literature AS grade_sum
) AS A
;
答案 2 :(得分:0)
您是否尝试过使用平均别名?在Teradata中,可以在case语句中使用别名。请检查它是否可以在SQL服务器中使用?
select
examinee_grade_science as "Science Grade",
examinee_grade_math as "Math Grade",
examinee_grade_literature as "Literature Grade",
examinee_grade_science + examinee_grade_math + examinee_grade_literature as "TOTAL",
avg(examinee_grade_science + examinee_grade_math + examinee_grade_literature) as "AVERAGE",
case when AVERAGE < 93
then 'PASSED'
else 'FAILED'
end as "REMARKS"
from examinee
答案 3 :(得分:0)
尝试以下查询(未测试)
;with cte as (
select
examinee_grade_science as "Science Grade",
examinee_grade_math as "Math Grade",
examinee_grade_literature as "Literature Grade",
examinee_grade_science + examinee_grade_math + examinee_grade_literature as "TOTAL"
from examinee)
select *,avg(Total) as "Total",case when avg(Total)<93 then 'PASSED' else 'FAILED' end as "REMARKS" from cte