我有这四个表:
SELECT [B_Key]
,[B_FiscalYear]
,[B_OrgCode]
,[B_SubObject]
,[B_Explanation]
,[B_CIPrefNo]
,[B_OrgBudgetAmt]
,[B_BudgetAmt]
,[B_Initials]
FROM [NAOLI].[dbo].[BudgetTbl]
SELECT [F_Fykey]
,[F_FiscalYear]
,[F_Year]
FROM [NAOLI].[dbo].[codeFiscalYearTbl]
SELECT [O_OrgKey]
,[O_OrgCode]
,[O_OrgDesc]
,[O_Divisions]
FROM [NAOLI].[dbo].[codeOrgCodeTbl]
SELECT [S_SubKey]
,[S_SubObject]
,[S_SubDescrip]
FROM [NAOLI].[dbo].[codeSubObjectTbl]
我需要在这些表格中组合不同的信息,以便制作以下信息表:
[B_FiscalYear]
,[O_OrgCode]
,[O_OrgDesc]
,[S_SubObject]
,[S_SubDescrip]
,[B_BudgetAmt]
,[B_Initials]
,[B_CIPrefNo]
,[B_OrgBudgetAmt]
我尝试了下面的查询,但它返回了20750条记录中的0条..我该如何做到这一点?感谢
SELECT [B_FiscalYear]
,[B_OrgCode]
,[O_OrgDesc]
,[B_SubObject]
,[S_SubDescrip]
,[B_BudgetAmt]
,[B_Initials]
,[B_CIPrefNo]
,[B_OrgBudgetAmt]
INTO dbo.BudgetsTbl
FROM [BudgetTbl] BT, [codeFiscalYearTbl] FY, [codeOrgCodeTbl] OC, [codeSubObjectTbl] SO
WHERE BT.B_FiscalYear = FY.F_Year and BT.B_OrgCode = OC.O_OrgCode and BT.B_SubObject = SO.S_SubObject
答案 0 :(得分:1)
联接应该是这样的:
SELECT [B_FiscalYear]
,[B_OrgCode]
,[O_OrgDesc]
,[B_SubObject]
,[S_SubDescrip]
,[B_BudgetAmt]
,[B_Initials]
,[B_CIPrefNo]
,[B_OrgBudgetAmt]
FROM BudgetTbl BT
JOIN codeFiscalYearTbl FY ON BT.B_FiscalYear = FY.F_Year
JOIN codeOrgCodeTbl OC ON BT.B_OrgCode = OC.O_OrgCode
JOIN codeSubObjectTbl SO ON BT.B_SubObject = SO.S_SubObject
您可以查看http://sqlfiddle.com/#!3/8ff6b/7了解详情。 如果需要,您还可以添加左连接。
答案 1 :(得分:0)
正确的连接语法是:
SELECT [B_FiscalYear], [B_OrgCode], [O_OrgDesc], [B_SubObject], [S_SubDescrip],
[B_BudgetAmt], [B_Initials], [B_CIPrefNo], [B_OrgBudgetAmt]
INTO dbo.BudgetsTbl
FROM BudgetTbl BT join
codeFiscalYearTbl FY
on BT.B_FiscalYear = FY.F_Year join
codeOrgCodeTbl OC
on BT.B_OrgCode = OC.O_OrgCode join
codeSubObjectTbl SO
on BT.B_SubObject = SO.S_SubObject
据推测,您的一个或多个查找表为空。如果您想要所有行,请在上面的查询中将“join”替换为“left outer join”。