我想結合兩個表中沒有日期共同只有一個caseid。
這是我的SQL代碼。我也試圖結合EcoDate和ProductionMonth列,因爲它們都包含日期信息。結合2個表,沒有日期共同
SELECT cmp.ProductionMonth, cmp.ProductionAmount, rce.EcoDate, rcl.CaseCaseId, cmp.CaseCaseId AS CaseId, rce.GrossOil
FROM PhdRpt.ReportCaseList_465 AS rcl INNER JOIN
PhdRpt.RptCaseEco_465 AS rce ON rcl.ReportRunCaseId = rce.ReportRunCaseId RIGHT OUTER JOIN
CaseMonthlyProduction AS cmp ON rcl.CaseCaseId = cmp.CaseCaseId
如果我運行此查詢的2分不同的人,我會得到這樣的輸出:
CaseCaseId-----EcoDate----GrossOil
12345------------2013-1-1------125.3
12345------------2013-2-1------15.3
12345------------2013-3-1------12.3
12345------------2013-4-1------125.0
12345------------2013-5-1------15.0
12345------------2013-6-1------120.3
12346------------2013-1-1------422.2
12346------------2013-2-1------325.2
12346------------2013-3-1------100.0
CaseId--------ProductionMonth------ProductionAmount
12345------------2016-1-1-----------------223.0
12345------------2016-2-1-----------------254.1
12345------------2016-3-1-----------------652.1
12345------------2016-4-1-----------------255.9
12346------------2016-1-1-----------------111.1
12346------------2016-2-1-----------------621.2
我的輸出表應該是這樣的:
CaseCaseId-------Date--------GrossOil--------ProductionAmount
12345------------2013-1-1------125.3-----------------null
12345------------2013-2-1------15.3------------------null
12345------------2013-3-1------12.3------------------null
12345------------2013-4-1------125.0-----------------null
12345------------2013-5-1------15.0------------------null
12345------------2013-6-1------120.3-----------------null
12345------------2016-1-1-------null------------------223.0
12345------------2016-2-1-------null------------------254.1
12345------------2016-3-1-------null------------------652.1
12345------------2016-4-1-------null------------------255.9
12346------------2013-1-1------422.2-----------------null
12346------------2013-2-1------325.2-----------------null
12346------------2013-3-1------100.0-----------------null
12346------------2016-1-1-------null------------------111.1
12346------------2016-2-1-------null------------------621.2
當我使用正確的外連接,它將返回數據庫中的所有CaseIds,而不僅僅是PhdRpt.ReportCaseList_465的一部分。另外,我不確定如何將兩個日期字段合併爲一個。任何建議表示讚賞!
謝謝catfood。 )後出現錯誤)。 Msg 156,Level 15,State 1,Line 20 關鍵字'order'附近的語法不正確。 –
這使它工作。 '選擇 rcl.ReportRunCaseId, rce.EcoDate如日期, rce.GrossOil, 0作爲ProductionAmount 從phdrpt.reportcaselist_465作爲RCL 上rcl.ReportRunCaseId = rce.ReportRunCaseId 工會 內部聯接phdrpt.rptcaseeco_465作爲RCE 選擇 rcl.ReportRunCaseId, cmp.ProductionMonth如日期, 0作爲GrossOil, cmp.ProductionAmount 從phdrpt.reportcaselist_465作爲RCL 內上rcl.ReportRunCaseId = cmp.CaseCaseId 爲了通過rcl.ReportRunCaseId加入CaseMonthlyProduction AS CMP ,日期' –
謝謝你的幫助。 –