2012-08-30 27 views
1

的insted的我有一個像下面自加入環

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 

爲此,現在寫我worte while循環。但它太過笨拙。我們可以使用連接來做到這一點嗎?謝謝。

+2

什麼是邏輯?爲什麼沒有匯率適用於賬戶5667? – Barmar

+0

@Barmar匯率未應用於5667,因爲第1次收回交易<< 65000075 5667 null -500 >>沒有匯率。 – Gokul

+1

但是賬戶5666的第一筆交易65000071沒有匯率,而您確實將匯率應用於交易65000072和65000073.有什麼區別? – Barmar

回答

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 
+0

感謝您的回答。但它也是對5667賬戶申請匯率。 – Gokul

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 
+0

謝謝你的回答。但對於一個沒有預付款(+ ve數額)的賬戶,我們不應該使用匯率。我編輯了我的表格<< Account 5669 >>。但查詢是應用匯率。 – Gokul

+0

再次編輯一點點。 –

+0

我收到以下錯誤<< Column'tMax.MaxAmount'在選擇列表中無效,因爲它不包含在聚合函數或GROUP BY子句中。>> – Gokul