链接行与sql server中的列

时间:2012-09-14 07:34:31

标签: sql-server-2005

我正在尝试使用两个表

来获取结果集
  1. Trail Balance
  2. 老化
  3. 表的结构是

    老化

    loc    |    glAcct    |    Amount
    -----------------------------------
    1013   |     1101     |    200
    -----------------------------------
    1211   |     1102     |    300
    -----------------------------------
    

    试算平衡

    loc   |    g1101    |   g1102
    ------------------------------
    1013  |     20      |    30
    ------------------------------
    1211  |     10      |    40
    -----------------------------
    

    现在我要做的是将行与列匹配 我现在想要的是

    loc   |   glAcct    |    agigingAmount |  Trialbalance Amount
    --------------------------------------------------------------
    1013  |     1101    |      200         |        20
    --------------------------------------------------------------
    1211  |     1102    |      300         |        40
    -------------------------------------------------------------     
    

    我尝试过像

    这样的案例陈述
    select ag.loc,ag.glAcct,
    case
       when ag.glAcct = '1101' then select g1101 from trialbalance 
       when ag.glAcct = '1102' then select gl101 from trialbalance 
    end  
    
     from trialbalance tb,Aging ag where ag.loc = tb.loc
    

    但它不起作用。

    提前感谢。

2 个答案:

答案 0 :(得分:2)

你快到了那里:

SELECT ag.loc, ag.glAcct, ag.Amount AS agigingAmount
CASE ag.glAcct
   WHEN '1101' THEN tb.g1101
   WHEN '1102' THEN tb.g1102
END AS [Trialbalance Amount]
FROM Aging ag
INNER JOIN trialbalance tb on ag.loc = tb.loc

答案 1 :(得分:1)

试试这个:

SELECT ag.loc,
ag.glAcct, 
ag.Amount AS agigingAmount,
TrialbalanceAmount=
CASE ag.glAcct
   WHEN '1101' THEN tb.g1101
   WHEN '1102' THEN tb.g1102
END
FROM Aging ag,trialbalance tb 
WHERE ag.loc = tb.loc;

Here is a working example