左外连接查询

时间:2011-05-09 04:55:11

标签: sql-server outer-join

in Image table - 1 is table with Primery key ID autonumber and DeclarationContentId as FK from another table. There are two column GrantedAmount and DeclaredAmount Identified by the another column AmountType. I want a left outer join query which will return me a for DeclartionContentId with GrantedAmount and DeclaredAmount togather in a single row extepecte output table shown below in the image

图像表中的

- 1是来自另一个表的Primery密钥ID自动编号和DeclarationContentId作为FK的表。有两列GrantedAmount和DeclaredAmount由另一列AmountType标识。我想要一个左外连接查询,它将返回给我一个与GrantedAmount的DeclartionContentId和在一行中的DeclaredAmount togather

1 个答案:

答案 0 :(得分:0)

在这里做一些假设

  • 这两个表格为declarationcontentdeclarationcontentamount
  • 您希望在类型为1
  • 时获得授予的金额
  • 您希望在类型为2
  • 时声明的金额
  • 您想要零而不是null
  • 左连接,因为每个declacontentid
  • 可能无法表示每种类型

试试这个

SELECT dc.declarationcontentid, 
       Isnull(ga.grantedamount, 0)  grantedamount, 
       Isnull(dc.declaredamount, 0) declaredamount 
FROM   declarationcontent dc 
       LEFT JOIN declarationcontentamount ga 
         ON dc.declarationcontentid = ga.declarationcontentid 
            AND amounttype = 1 
       LEFT JOIN declarationcontentamount dc 
         ON dc.declarationcontentid = ga.declarationcontentid 
            AND amounttype = 2