SQL查询组合来自两个表的数据

时间:2013-02-21 21:53:21

标签: sql sql-server-2008

我有以下查询从2个表格中收集一些信息(StudentsSubjects

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 )

3 个答案:

答案 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)

您可以尝试合并(合并)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

答案 2 :(得分:0)

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

SELECT * FROM TableA
UNION
SELECT * FROM TableB

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