我有以下查询从2个表格中收集一些信息(Students
和Subjects
)
SELECT
'StudentName' As Student,
'Class' As Class,
'Subject' As Subject
DATEDIFF( HOUR, hoursSpent.ClassStartTime, hoursSpent.ClassEndTime ) As HoursSpent
FROM (
SELECT stu.StudentName from Students s
INNER JOIN Subjects sub
WHERE stu.StudentId = sub.StudentId
) hoursSpent
我有另一个表与布局中Students
表完全相同的表称为OldStudents
。
我的问题是我想要合并来自Students
和OldStudents
的数据并显示为一个但不知道我该怎么做。
我尝试了这个,但这不起作用:
SELECT
'StudentName' As Student,
'Class' As Class,
'Subject' As Subject
DATEDIFF( HOUR, hoursSpent.ClassStartTime, hoursSpent.ClassEndTime ) As HoursSpent
SELECT(
FROM (
SELECT stu.StudentName from Students s
INNER JOIN Subjects sub
WHERE stu.StudentId = sub.StudentId
) hoursSpent,
FROM (
SELECT stu.StudentName from Students s
INNER JOIN Subjects sub
WHERE stu.StudentId = sub.StudentId
) hoursSpent )
答案 0 :(得分:2)
基本上,您需要有两个相同的查询,每个表一个,并使用UNION
(或UNION ALL
连接它们:
SELECT
'StudentName' As Student,
'Class' As Class,
'Subject' As Subject
DATEDIFF( HOUR, hoursSpent.ClassStartTime, hoursSpent.ClassEndTime ) As HoursSpent
FROM (
SELECT stu.StudentName from Students s
INNER JOIN Subjects sub
WHERE stu.StudentId = sub.StudentId
) hoursSpent
UNION ALL
SELECT
'StudentName' As Student,
'Class' As Class,
'Subject' As Subject
DATEDIFF( HOUR, hoursSpent.ClassStartTime, hoursSpent.ClassEndTime ) As HoursSpent
FROM (
SELECT stu.StudentName from OldStudents s
INNER JOIN Subjects sub
WHERE stu.StudentId = sub.StudentId
) hoursSpent
UNION
会使结果明显,UNION ALL
不会。
答案 1 :(得分:1)
您可以尝试合并(合并)Students
和OldStudents
,然后将结果加入到查询的其余部分:
WITH AllStudents
AS (
SELECT * FROM Students
UNION
SELECT * FROM OldStudents
)
SELECT
'StudentName' As Student,
'Class' As Class,
'Subject' As Subject
DATEDIFF( HOUR, hoursSpent.ClassStartTime, hoursSpent.ClassEndTime ) As HoursSpent
FROM (
SELECT stu.StudentName from AllStudents stu
INNER JOIN Subjects sub
WHERE stu.StudentId = sub.StudentId
) hoursSpent
答案 2 :(得分:0)
如果您只想将一组数据添加到另一组,请使用UNION运算符:
SELECT * FROM TableA
UNION
SELECT * FROM TableB
每个SELECT语句必须具有相同的列数