如何组合这两个查询

时间:2013-11-02 01:14:16

标签: sql oracle union-all

我对两个查询都使用相同的表和列,但我有不同的别名和avg函数。我怎样才能将这两个查询与UNION ALL结合起来,因为我想要从中选择每一行。当我有不同的select语句时,显然我不能这样做。我怎么能把这两个问题结合起来呢?

SELECT GRADE_TYPE_CODE, ROUND(TO_CHAR(NUMERIC_GRADE),2) AS GRADE
FROM GRADE
WHERE STUDENT_ID = 10 AND SECTION_ID = 5
ORDER BY GRADE_TYPE_CODE DESC,NUMERIC_GRADE DESC;



SELECT 'Average is:' AS GRADE_TYPE_CODE,AVG(GRADE) AS GRADE
FROM
(
    SELECT AVG(NUMERIC_GRADE) AS GRADE
FROM GRADE
WHERE STUDENT_ID = 10 AND SECTION_ID = 5
GROUP BY GRADE_TYPE_CODE
) myInnerTable;

2 个答案:

答案 0 :(得分:3)

不确定这里的问题是什么。为什么不在你的两个查询之间加上“union all”,并将ORDER BY子句移到最后?

SELECT GRADE_TYPE_CODE, ROUND(TO_CHAR(NUMERIC_GRADE),2) AS GRADE
FROM GRADE
WHERE STUDENT_ID = 10 AND SECTION_ID = 5

union all

SELECT 'Average is:' AS GRADE_TYPE_CODE,AVG(GRADE) AS GRADE
FROM
(
    SELECT AVG(NUMERIC_GRADE) AS GRADE
FROM GRADE
WHERE STUDENT_ID = 10 AND SECTION_ID = 5
GROUP BY GRADE_TYPE_CODE
) myInnerTable

order by 1 desc, 2 desc

http://sqlfiddle.com/#!4/99a16/19/0

答案 1 :(得分:1)

我想你可以create a temporary table然后从两个单独的查询中结合ALL。