0

我有这四个表:

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
4

2 回答 2

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了解更多信息。如果需要,您也可以添加左连接。

于 2012-05-25T14:26:09.543 回答
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”。

于 2012-05-25T14:17:09.987 回答