以下查询在包含2个字段的表上执行:BEGDATE和AMOUNT(均为varchar2)。 目的是显示如下数据:
Year Semester Total
2017 Sem1 545
2017 Sem2 9877
2020 Sem1 444
这个想法是根据年份和学期计算字段数量的总和。 以下查询能够返回以下内容:
Year Semester
2017 Sem1
2017 Sem2
2020 Sem1
我应该在哪里使用SUM(TO_NUMBER(AMOUNT))
才能达到预期的效果?
SELECT DISTINCT(SUBSTR (BEGDATE, 1, 4)) AS YEAR,
CASE
WHEN SUBSTR (BEGDATE, 5, 2) BETWEEN 1 AND 3
THEN 'SEM1'
WHEN SUBSTR (BEGDATE, 5, 2) BETWEEN 4 AND 6
THEN 'SEM2'
WHEN SUBSTR (BEGDATE, 5, 2) BETWEEN 7 AND 9
THEN 'SEM3'
ELSE 'SEM4'
END SEMESTER
FROM EMP
ORDER BY YEAR DESC,SEMESTER
答案 0 :(得分:0)
只需在选择列列表的末尾添加一个总和即可。
SELECT SUBSTR (begdate, 1, 4) AS YEAR,
CASE
WHEN SUBSTR (begdate, 5, 2) BETWEEN 1 AND 3
THEN 'SEM1'
WHEN SUBSTR (begdate, 5, 2) BETWEEN 4 AND 6
THEN 'SEM2'
WHEN SUBSTR (begdate, 5, 2) BETWEEN 7 AND 9
THEN 'SEM3'
ELSE 'SEM4'
END semester,
SUM (TO_NUMBER (amount)) sum_val
FROM emp
GROUP BY SUBSTR (begdate, 1, 4),
CASE
WHEN SUBSTR (begdate, 5, 2) BETWEEN 1 AND 3
THEN 'SEM1'
WHEN SUBSTR (begdate, 5, 2) BETWEEN 4 AND 6
THEN 'SEM2'
WHEN SUBSTR (begdate, 5, 2) BETWEEN 7 AND 9
THEN 'SEM3'
ELSE 'SEM4'
END
ORDER BY YEAR DESC, semester;
此外,当你正在分组时,你不再需要它了。
答案 1 :(得分:0)
添加了SUM
SELECT A.YEAR,A.SEMESTER, SUM(TO_NUMBER(A.AMOUNT)) AS SUM_AMT
FROM
(SELECT DISTINCT(SUBSTR (BEGDATE, 1, 4)) AS YEAR,
CASE
WHEN SUBSTR (BEGDATE, 5, 2) BETWEEN 1 AND 3
THEN 'SEM1'
WHEN SUBSTR (BEGDATE, 5, 2) BETWEEN 4 AND 6
THEN 'SEM2'
WHEN SUBSTR (BEGDATE, 5, 2) BETWEEN 7 AND 9
THEN 'SEM3'
ELSE 'SEM4'
END SEMESTER,
AMOUNT
FROM EMP
ORDER BY YEAR DESC,SEMESTER)A
GROUP BY YEAR,SEMESTER
ORDER BY YEAR DESC, SEMESTER;