我有一個表如下。使用重複列計數
ClientID | FileCount | LinkNumber | ActualFileCount |
----------|-----------|------------|-----------------|
1 | 1 | 0 | 1 |
----------|-----------|------------|-----------------|
2 | 1 | 0 | 1 |
----------|-----------|------------|-----------------|
3 | 2 | 0 | 2 |
----------|-----------|------------|-----------------|
4 | 1 | 123 | 1 |
----------|-----------|------------|-----------------|
5 | 1 | 123 | 0 |
----------|-----------|------------|-----------------|
6 | 2 | 456 | 2 |
----------|-----------|------------|-----------------|
7 | 2 | 456 | 0 |
----------|-----------|------------|-----------------|
8 | 2 | 456 | 0 |
----------|-----------|------------|-----------------|
9 | 1 | 789 | 1 |
----------|-----------|------------|-----------------|
10 | 1 | 789 | 0 |
基本上,如果LinkNumber爲0,則將FileCount列複製到ActualFileCount列中。但是,如果LinkNumber不是0,那麼ActualFileCount必須只是與該LinkNumber相關的單個值。
例如ClientID 4和5,他們是夫妻,所以我們把他們倆連起來。系統給它們每個FileCount 1.但是,因爲它們是鏈接,所以兩者都只有一個ActualFileCount(兩者都只有1個「物理」文件)。
我使用的語法如下練成我(使用客戶端ID 3和客戶端Id 4爲例)
If (LinkNumber = 0 then FileCount else
(If (LinkNumber for ClientID 4 = LinkNumber for ClientID 3 then 0 else FileCount)
當我把它翻譯到SQL Server 2012,這是行不通的。
select ClientID, file_count, LinkNumber,
If LinkNumber = 0 then file_count
else If LinkNumber + 1 = LinkNumber Then 0 else FileCount
end
as ActualFileCount
from TableA
order by LinkNumber asc
謝謝你們的幫助。
我猜你可能會尋找當linknumber = 0或ROW_NUMBER()通過像'情況下在(分區linknumber order by clientid)= 1 then file_count else 0 end'? – ZLK