Rya*_*eif 6 sql t-sql sql-server
我有两张桌子.一个是提交给我们的报告表.另一个是临时表,其中包含最终应提交给我们的报告记录.我想只显示临时表中与报告表中的记录不匹配的记录(因此显示仍然必须提交的报告).
示例数据是:
Reports table:
CREATE TABLE [dbo].[Reports]
(
[ReportID] [int] IDENTITY(1,1) NOT NULL,
[ReportDate] [date] NULL,
[AssessmentID] [int] NOT NULL,
[ReportType] [varchar](50) NULL
);
AssessmentID ReportType ReportID
1 1st Quarterly 27
2 1st Quarterly 30
2 2nd Quarterly 31
2 3rd Quarterly 32
QuarterlyReportsDue table:
CREATE TABLE #QuarterlyReportsDue
(
AssessmentID INT,
InstallationDate DATE,
QuarterlyReportType VARCHAR(50)
);
AssessmentID InstallationDate QuarterlyReportType
1 2009-08-14 1st Quarterly
1 2009-08-14 2nd Quarterly
1 2009-08-14 3rd Quarterly
1 2009-08-14 4th Quarterly
2 2008-05-16 4th Quarterly
2 2008-05-16 3rd Quarterly
2 2008-05-16 2nd Quarterly
2 2008-05-16 1st Quarterly
Run Code Online (Sandbox Code Playgroud)
我尝试过LEFT OUTER JOINS,但遇到了问题.请看下面的SQL:
SELECT #QuarterlyReportsDue.InstallationDate, #QuarterlyReportsDue.QuarterlyReportType, Reports.ReportType
FROM #QuarterlyReportsDue
LEFT OUTER JOIN Reports ON #QuarterlyReportsDue.AssessmentID = Reports.AssessmentID
WHERE Reports.ReportType IN ('1st Quarterly', '2nd Quarterly', '3rd Quarterly', '4th Quarterly')
AND Reports.ReportType <> #QuarterlyReportsDue.QuarterlyReportType
ORDER BY #QuarterlyReportsDue.AssessmentID
Run Code Online (Sandbox Code Playgroud)
我的结果是:
AssessmentID QuarterlyReportType ReportType ReportID
1 2nd Quarterly 1st Quarterly 27
1 3rd Quarterly 1st Quarterly 27
1 4th Quarterly 1st Quarterly 27
2 4th Quarterly 1st Quarterly 30
2 4th Quarterly 2nd Quarterly 31
2 4th Quarterly 3rd Quarterly 32
2 1st Quarterly 2nd Quarterly 31
2 1st Quarterly 3rd Quarterly 32
2 3rd Quarterly 1st Quarterly 30
2 3rd Quarterly 2nd Quarterly 31
2 2nd Quarterly 1st Quarterly 30
2 2nd Quarterly 3rd Quarterly 32
Run Code Online (Sandbox Code Playgroud)
对于评估1,它很有效,评估2有很多重复.我怎样才能解决这个问题才能显示出理想的结果呢?
AssessmentID QuarterlyReportType ReportType
1 2nd Quarterly 1st Quarterly
1 3rd Quarterly 1st Quarterly
1 4th Quarterly 1st Quarterly
2 4th Quarterly
Run Code Online (Sandbox Code Playgroud)
当您将JOFT JOIN连接到表然后引用WHERE子句中该表的一个列时,您将隐式地将连接转换为INNER JOIN.相反,将这些条件移出WHERE并使它们成为JOIN条件的一部分.
SELECT q.InstallationDate, q.QuarterlyReportType, Reports.ReportType
FROM #QuarterlyReportsDue q
LEFT OUTER JOIN Reports r
ON q.AssessmentID = r.AssessmentID
AND q.QuarterlyReportType = r.ReportType
AND r.ReportType IN ('1st Quarterly', '2nd Quarterly', '3rd Quarterly', '4th Quarterly')
WHERE r.AssessmentID IS NULL /* matching record not found in Reports table */
ORDER BY #QuarterlyReportsDue.AssessmentID
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
19131 次 |
最近记录: |