我在 MS SQL Server “MyTable”中有一个表格,如下所示 -
PkId | Title | Some Column
-----------------------------------------------
1 | User 2 | Some value for "User 2"
-----------------------------------------------
2 | User | Some value for the user
-----------------------------------------------
3 | User | Some value for the user
-----------------------------------------------
4 | Admin | Some value for the Admin
-----------------------------------------------
5 | Guest 1 | Some value for "Guest 1"
-----------------------------------------------
6 | Guest | Some value for the guest
我希望得到像
这样的输出User 1 - Some value for the user
User 2 - Some value for "User 2" [Note - this "User 2" title was existing and this keeps the "Some Column" value intact as well]
User 3 - Some value for the user
Admin 1 - Some value for the Admin
Guest 1 - Some value for "Guest 1" [Note - Existing title with existing value]
Guest 2 - Some value for the guest
[我不关心订购,但是想要像上面那样映射用户,以便我可以在标题后获得数字(如果标题已经包含了跳过该编号的编号并且没有复制相同的编号) “Some Column”值保持原样]
我尝试过排名超过分区但没有达到预期的结果。请帮帮我。
答案 0 :(得分:1)
此查询应该执行您想要的操作。这可能是有用的,正如其他人所说的那样,将用户和数字存储在这样的字符串中可能是一个好主意。
<强>查询:强>
// do writing
while (some condition) {
format.writeRecord(record);
}
// finished writing
format.close();
With titles as (
SELECT distinct title = title FROM @MyTable
WHERE NOT RIGHT(title, 1) LIKE '[0-9]'
), numbers as (
SELECT n = ROW_NUMBER() over(PARTITION BY t.title ORDER BY pkid DESC)
, pkid
, Name
, grp = t.title
, id = TRY_PARSE(CASE WHEN d.title NOT LIKE t.title THEN RIGHT(d.title, ABS(LEN(d.title) - LEN(t.title))) END as bigint)
, missing = ROW_NUMBER() over(PARTITION BY t.title, CASE WHEN d.title NOT LIKE t.title THEN 0 ELSE 1 END ORDER BY pkid DESC)
FROM @MyTable d
INNER JOIN titles t ON d.title LIKE t.title+'%'
), new_n as (
SELECT n, grp, id = ROW_NUMBER() over(PARTITION BY grp ORDER BY n)
FROM (
SELECT n, grp
FROM numbers
EXCEPT
SELECT id, grp
FROM numbers
WHERE id IS NOT NULL
) as x
)
SELECT nb.pkid, n = coalesce(nb.id, nw.n), nw.grp+CAST(coalesce(nb.id, nw.n) as varchar(5)), nb.name--, *
FROM numbers nb
LEFT JOIN new_n nw ON nb.grp = nw.grp AND nb.missing = nw.id
ORDER BY nb.pkid
查找不带编号的不同标题(用户,管理员和访客)titles
按组标题(n)对其进行分区,获取现有标题的ID(id)和按组标题分区,以及ID是否缺失(缺失)<强>输出:强>
number
数据:强>
pkid n title name
1 2 User2 Some value for "User 2"
2 3 User3 Some value for the user
3 1 User1 Some value for the user
4 1 Admin1 Some value for the Admin
5 1 Guest1 Some value for "Guest 1"
6 2 Guest2 Some value for the guest
答案 1 :(得分:0)
使用它:
select 'user ' + (case when patindex('%[0-9]%',title) = 0 then row_number() over (partition by title order by (select 1)) else substring(title,patindex('%[0-9]%',title),1) end) + '-' + somecolumn
from table1
如果数字始终位于标题栏的末尾,您可以使用 -
select 'user ' + (case when isnumeric(right(title,1)) = 1 then right(title,1) else row_number() over (partition by title order by (select 1)) end) + '-' + somecolumn
from table1