SQL服务器加入多个表

时间:2013-03-05 07:16:26

标签: sql sql-server-2008

我有6个包含学生信息的表格。它们共享相同的列名,但具有不同的数据。那么,问题是如何在六年期间由学术学院按学期报告学生人口统计数据?你会在这类问题中使用左连接吗?我试图使用内连接但它不起作用。实际上,这就是我所做的:

SELECT DOB, SEX, RACE, MAJORCOLLEGE

FROM MasterFile2006

Join MasterFile2007 ON MasterFile2006.HOMEID = MasterFile2007.HOMEID

Join MasterFile2008 ON MasterFile2006.HOMEID = MasterFile2008.HOMEID

Join MasterFile2009 ON MasterFile2006.HOMEID = MasterFile2009.HOMEID

Join MasterFile2010 ON MasterFile2006.HOMEID = MasterFile2010.HOMEID

Join MasterFile2011 ON MasterFile2006.HOMEID = MasterFile2011.HOMEID

我真的很感谢你的帮助!!

2 个答案:

答案 0 :(得分:4)

使用UNION

SELECT DOB, SEX, RACE, MAJORCOLLEGE, '2006' as [Year] FROM MasterFile2006
UNION ALL
SELECT DOB, SEX, RACE, MAJORCOLLEGE, '2007' as [Year] FROM MasterFile2007
UNION ALL
SELECT DOB, SEX, RACE, MAJORCOLLEGE, '2008' as [Year] FROM MasterFile2008
UNION ALL
SELECT DOB, SEX, RACE, MAJORCOLLEGE, '2009' as [Year] FROM MasterFile2009
UNION ALL
SELECT DOB, SEX, RACE, MAJORCOLLEGE, '2010' as [Year] FROM MasterFile2010
UNION ALL
SELECT DOB, SEX, RACE, MAJORCOLLEGE, '2011' as [Year] FROM MasterFile2011

注意:UNION ALL不会丢弃重复项(并且不应该重复),UNION会执行DISTINCT并丢弃重复的行。

答案 1 :(得分:1)

  

您需要使用UNION ALLUNION。如果您需要UNION条记录,请使用DISTINCT

SELECT DOB, SEX, RACE, MAJORCOLLEGE FROM MasterFile2006
UNION
SELECT DOB, SEX, RACE, MAJORCOLLEGE FROM MasterFile2007
UNION
SELECT DOB, SEX, RACE, MAJORCOLLEGE FROM MasterFile2008
UNION
SELECT DOB, SEX, RACE, MAJORCOLLEGE FROM MasterFile2009
UNION
SELECT DOB, SEX, RACE, MAJORCOLLEGE FROM MasterFile2010
UNION
SELECT DOB, SEX, RACE, MAJORCOLLEGE FROM MasterFile2011