Need help to write a query?

답변됨 Need help to write a query?

  • 2012년 7월 23일 월요일 오전 9:35
     
     

     I have two tables as:

    1) tblChartOfAccount

    Fields:

    AcctKey (bigint)  ==>PrimaryKey

    AcctName(varchar)

    and another table

    2) tblJournalEntry

    Fields:

    TransID (bigint)

    GLAcctKey (bigint) ==>ForiegnKey to tblChartOfAccount.AcctKey

    ControlAcctKey (bigint) ==>ForiegnKey to tblChartOfAccount.AcctKey

    Now I want to get data from second table tblJournalEntry in this form:

    TransID, GLAcctName, ControlAcctName,

    i.e I need in output both account's names instead of their keys. I am confused that I am able to write a join only on one PKcolum to one FKcolum.  But how can write join for two FKcolums to one PKcolumns?





    • 편집됨 Rana76 2012년 7월 23일 월요일 오전 9:36
    • 편집됨 Rana76 2012년 7월 23일 월요일 오전 9:37
    • 편집됨 Rana76 2012년 7월 23일 월요일 오전 9:37
    • 편집됨 Rana76 2012년 7월 23일 월요일 오전 9:39
    •  

모든 응답

  • 2012년 7월 23일 월요일 오전 9:43
     
     답변됨 코드 있음

    Are you looking for the below Solution

    Create Table tblChartOfAccount (AcctKey Bigint , AcctName Varchar(50))
    Insert into tblChartOfAccount Values (101,'GLNAme')
    Insert into tblChartOfAccount Values (102,'ControlNAme')
    Create Table tblJournalEntry (TransID Bigint, GLAcctKey  Bigint , ControlAcctKey  Varchar(50))
    Insert into tblJournalEntry Values (1011,101,102)
    Select A.TransID,B.AcctName,C.AcctName From tblJournalEntry A
    Left Join tblChartOfAccount B On A.GLAcctKey = B.AcctKey 
    Left Join tblChartOfAccount C On A.ControlAcctKey = C.AcctKey

    • 답변으로 표시됨 Rana76 2012년 7월 23일 월요일 오전 9:58
    •  
  • 2012년 7월 23일 월요일 오전 9:44
     
     답변됨 코드 있음
    Select A.TransID, B.AcctName As GLAcctName, C.AcctName AS ControlAcctName
    From tblJournalEntry A
    Inner Join
    tblChartOfAccount B
    on A.GLAcctKey = B.AcctKey
    Inner Join
    tblChartOfAccount C
    on A.ControlAcctKey = C.AcctKey


    View Steven Wang's profile on LinkedIn | Blog: MSBICOE.com | MCITP - BI, SQL Developer & DBA

    Hate to mislead others, if I'm wrong slap me. Thanks!

    • 답변으로 표시됨 Rana76 2012년 7월 23일 월요일 오전 9:58
    •