1

我有一张如下表

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

为此,现在写我写的while循环。但这太过分了。我们可以使用连接来做到这一点吗?谢谢你。

4

2 回答 2

1
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
于 2012-08-30T08:27:13.740 回答
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
于 2012-08-30T08:12:04.360 回答