![](/img/trans.png)
[英]Create a table with maximum values out of 2 combined tables in SQL Server
[英]Creating a string of combined values from a SQL Server table
我建立了一個SQL查詢,該查詢返回以下結果:
ID Number ID IndexColumn String_To_Use Checking_ID
0000 1 0000 1 -2
1000 2 1000 2 -2
1020 3 1020 3 -2
1130 4 1130 4 -2
1198 5 NULL 9999 NULL NULL
1199 6 1199 5 -2
1210 7 1210 6 -2
1240 8 NULL 9999 NULL NULL
1250 9 NULL 9999 NULL NULL
1260 10 1260 7 7
1261 11 NULL 9999 NULL NULL
1280 12 NULL 9999 NULL NULL
1296 13 NULL 9999 NULL NULL
1298 14 NULL 9999 NULL NULL
1299 15 1299 8 8
1501 16 NULL 9999 NULL NULL
我需要以“ ID”值填充“ String_To_Use”列,如果“ Checking_ID”列的值大於-2重復一次(這意味着用戶選擇了范圍內的ID),則這些重復值將顯示為“0000-1130”; 如果未重復值-2,則為“ 1260”。 基於此邏輯,上表將在String_To_Use列中包含以下值:
ID Number ID IndexColumn String_To_Use Checking_ID
0000 1 0000 1 0000-1130 -2
1000 2 1000 2 0000-1130 -2
1020 3 1020 3 0000-1130 -2
1130 4 1130 4 0000-1130 -2
1198 5 NULL 9999 NULL NULL
1199 6 1199 5 0000-1210 -2
1210 7 1210 6 0000-1210 -2
1240 8 NULL 9999 NULL NULL
1250 9 NULL 9999 NULL NULL
1260 10 1260 7 1260 7
1261 11 NULL 9999 NULL NULL
1280 12 NULL 9999 NULL NULL
1296 13 NULL 9999 NULL NULL
1298 14 NULL 9999 NULL NULL
1299 15 1299 8 1299 8
1501 16 NULL 9999 NULL NULL
謝謝!!
您需要定義“鄰接”組。 在這種情況下,您可以簡單地對checking_id
不是-2
的次數進行累加。
之后,剩下的就是窗口函數和字符串操作了:
select t.*,
(case when checking_id <> -2
then min(id) over (partition by grp) + '-' + max(id) over (partition by grp)
else id
end) as string_to_use
from (select t.*,
sum(case when checking_id <> -2 then 1 else 0 end) over (order by id) as grp
from t
) t;
此版本假定id
是一個字符串。 如果是數字,則可以通過使用cast()
或convert()
使代碼混亂,從而輕松地修改代碼。
select t.*,
(case when Checking_id = -2
then min(id) over (partition by grp) + '-' + max(id) over (partition by grp)
else id
end) as string_to_use
from (select t.*
,sum(case when Checking_id = -2 then 1 else 0 end) over (partition by id) as grp
from t
) t order by id;
ID Number ID IndexColumn String_To_Use Checking_id grp string_to_use
0000 1 0000 1 -2 1 0000 -1210
1000 2 1000 2 -2 1 0000 -1210
1020 3 1020 3 -2 1 0000 -1210
1130 4 1130 4 -2 1 0000 -1210
1198 5 NULL 9999 NULL NULL 0 NULL
1199 6 1199 5 -2 1 0000 -1210
1210 7 1210 6 -2 1 0000 -1210
1240 8 NULL 9999 NULL NULL 0 NULL
1250 9 NULL 9999 NULL NULL 0 NULL
1260 10 1260 7 7 0 1260
1261 11 NULL 9999 NULL NULL 0 NULL
1280 12 NULL 9999 NULL NULL 0 NULL
1296 13 NULL 9999 NULL NULL 0 NULL
1298 14 NULL 9999 NULL NULL 0 NULL
1299 15 1299 8 8 0 1299
1501 16 NULL 9999 NULL NULL 0 NULL
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.