自连接而不是循环

时间:2012-08-30 06:59:33

标签: sql-server-2008

我有一张如下表格

DocNo       Account ExRate  Amount
65000071    5666    null    1000
65000072    5666    4.3     -290
65000073    5666    5.9     -290
65000074    5667    null    4500
65000075    5667    null    -500
65000076    5667    2.3     -500
65000077    5667    1.6     -500
65000078    5668    null    3450
65000079    5668    7.4     -453
65000080    5668    8.1     -453
65000081    5668    8.4     -453
65000082    5668    7.9     -453
 65000081   5669    8.4     -453
    65000082    5669    7.9     -453

我需要运用汇率。只需挑选第一笔交易。以下是输出

DocNo   Account ExRate  Amount  
65000071    5666    null    1000    
65000072    5666    4.3    -1247    (-290*4.3)
65000073    5666    5.9    -1247    (-290*4.3)
65000074    5667    null    4500    
65000075    5667    null    -500    
65000076    5667    2.3     -500    
65000077    5667    1.6     -500    
65000078    5668    null    3450    
65000079    5668    7.4  -3352.2    (-453*7.4)
65000080    5668    8.1  -3352.2    (-453*7.4)
65000081    5668    8.4  -3352.2    (-453*7.4)
65000082    5668    7.9  -3352.2    (-453*7.4)
65000081     5669   8.4     -453
65000082    5669    7.9     -453

为此,请立即写入循环播放。但这太糟糕了。我们可以使用连接来完成此操作。谢谢。

2 个答案:

答案 0 :(得分:2)

SELECT  tbl.DocNo, tbl.Account, tbl.ExRate,
        CASE WHEN tbl.Amount < 0 THEN (tbl.Amount * t.NewExRate)
            ELSE tbl.Amount END
        AS NewAmount
FROM table tbl
LEFT OUTER JOIN (
                SELECT  t1.Account,
                        CASE WHEN tMin.MaxAmount >= 0 THEN ISNULL(t1.ExRate,1)
                            ELSE 1 END
                        AS NewExRate
                FROM    table t1
                LEFT OUTER JOIN (SELECT t2.Account,MIN(t2.DocNo) AS MinDocNo,tMax.MaxAmount
                                FROm    table t2
                                LEFT OUTER JOIN (SELECT t3.Account,MAX(t3.Amount) AS MaxAmount
                                            FROm    table t3
                                            GROUP BY t3.Account)tMax
                                ON t2.Account = tMax.Account
                                WHERE   t2.Amount < 0
                                GROUP BY t2.Account, tMax.MaxAmount
                                ) tMin
                ON t1.Account = tMin.Account
                WHERE t1.DocNo = tMin.DocNo
                )t
ON tbl.Account = t.Account

答案 1 :(得分:0)

select DocNo, t.Account as Account, t.ExRate as ExRate,
       case when Amount >= 0 then Amount
            else Amount * coalesce(t1.ExRate, 1)
       end as Amount
from MyTable as t
left outer join
     (select m.Account as Account, ExRate
      from MyTable as t
      join (select Account, min(DocNo) as MinDoc
            from MyTable
            where ExRate is not null and Amount < 0
            group by Account) as m
      on t.DocNo = m.MinDoc) as t1
on t.Account = t1.Account
order by DocNo