[英]SQL - 2 SELECT statements with UNION and WITH
I have a WITH
statement (I want to do some calculations on the results that why I am using with) and a SELECT
. 我有一个
WITH
语句(我想对为什么使用with的结果进行一些计算)和一个SELECT
。
Let's say that the SELECT
statement is collecting the 20 students with the best grade. 假设
SELECT
语句正在收集20位成绩最好的学生。
Now I want to get the 20 students with the worst grade so I tried another 现在我想让20名成绩最差的学生,所以我尝试了另一种
WITH cteGrades AS
(
SELECT *
FROM tbl_students
)
--Selecting best Grade
SELECT TOP(20)
cte.name, cte.surname, cte.grade
FROM
cteGrade cte
ORDER BY
cte.grade DESC
UNION
--Selecting worst Grade
SELECT TOP(20)
cte.name, cte.surname, cte.grade
FROM
cteGrades cte
ORDER BY
cte.grade ASC
I get the error: 我得到错误:
Incorrect syntax near the keyword 'UNION'.
关键字“ UNION”附近的语法不正确。
You should remove order by
in the union clause. 您应该在union子句中删除
order by
。 Do the ordering after the union
on the entire result-set. 后做排序
union
对整个结果集。 Or have the queries as cte
s and perform a union
on the results. 或者将查询作为
cte
并对结果执行并union
。
WITH cteGrade AS
(
SELECT *
FROM tbl_students
)
--Selecting best Grade
, top20 as
(SELECT TOP(20)
cte.name
,cte.surname
,cte.grade
FROM cteGrade cte
ORDER BY cte.grade DESC)
, last20 as
(
--Selecting worst Grade
SELECT TOP(20)
cte.name
,cte.surname
,cte.grade
FROM cteGrade cte
ORDER BY cte.grade ASC
)
select name, surname, grade from top20
union all
select name, surname, grade from last20
WITH cteGrades AS
(
SELECT *
,ROW_NUMBER() OVER (ORDER BY grade DESC) Best_Grades
,ROW_NUMBER() OVER (ORDER BY grade ASC ) Worst_Grades
FROM tbl_students
)
SELECT cte.name
,cte.surname
,cte.grade
FROM cteGrades cte
WHERE Best_Grades <= 20
OR Worst_Grades <= 20
ORDER BY cte.grade DESC
Your original query is just missing parentheses around the subqueries: 您原来的查询只是在子查询周围缺少括号:
WITH cteGrades AS (
SELECT *
FROM tbl_students
)
--Selecting best Grade
(SELECT TOP(20) cte.name, cte.surname, cte.grade
FROM cteGrade cte
ORDER BY cte.grade DESC
) UNION
(SELECT TOP(20) cte.name, cte.surname, cte.grade
FROM cteGrades cte
ORDER BY cte.grade ASC
);
Rewriting to use CTEs or row numbers is also possible, but there is really no reason to do that. 也可以重写以使用CTE或行号,但是实际上没有理由这样做。
Actually, you don't need a CTE at all for this: 实际上,您完全不需要CTE:
(SELECT TOP(20) s.name, s.surname, s.grade
FROM tbl_students s
ORDER BY s.grade DESC
) UNION
(SELECT TOP(20) s.name, s.surname, s.grade
FROM tbl_students s
ORDER BY s.grade ASC
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.