1

我有 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

我将衷心感谢您的帮助!!

4

2 回答 2

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执行 aDISTINCT并丢弃重复的行。

于 2013-03-05T07:18:20.543 回答
1

您需要使用UNION ALLUNIONUNION如果您需要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
于 2013-03-05T07:23:22.903 回答