2

Students我有以下查询,它从 2 个表(和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.

我的问题是我想将两者的数据结合起来StudentsOldStudents显示为一个,但不知道如何做到这一点。

我试过了,但这不起作用:

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 )
4

3 回答 3

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不会。

于 2013-02-21T22:00:35.627 回答
1

您可以尝试组合(联合)StudentsOldStudents然后将结果加入查询的其余部分:

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
于 2013-02-21T22:02:44.870 回答
0

如果您只想将一组数据添加到另一组,请使用 UNION 运算符:

SELECT * FROM TableA
UNION
SELECT * FROM TableB

每个 SELECT 语句必须具有相同的列数

于 2013-02-21T21:57:42.760 回答