请教一个SQL语句实现:如下
字段1 字段2
1 管理
2 其他
3 管理
4 管理
5 其他
6 管理
7 管理
....
怎么变为:
字段1 字段2
1 管理1
2 其他1
3 管理2
4 管理3
5 其他2
6 管理4
7 管理5
....
就是把 字段2 相同的值都分别加上 1、2、3。。。。
[解决办法]
if object_id( 'pubs..tb ') is not null
drop table tb
go
create table tb
(
字段1 varchar(10),
字段2 varchar(10)
)
insert into tb(字段1,字段2) values( '1 ', '管理 ')
insert into tb(字段1,字段2) values( '2 ', '其他 ')
insert into tb(字段1,字段2) values( '3 ', '管理 ')
insert into tb(字段1,字段2) values( '4 ' , '管理 ')
insert into tb(字段1,字段2) values( '5 ' , '其他 ')
insert into tb(字段1,字段2) values( '6 ', '管理 ')
insert into tb(字段1,字段2) values( '7 ', '管理 ')
select 字段1 , rtrim(字段2) + cast(px as varchar(10)) as 字段2 from
(
select px=(select count(1) from tb where 字段2=a.字段2 and 字段1 <a.字段1)+1 , * from tb a
) t
order by 字段1
drop table tb
--result
字段1 字段2
---------- --------------------
1 管理1
2 其他1
3 管理2
4 管理3
5 其他2
6 管理4
7 管理5
(所影响的行数为 7 行)
[解决办法]
DECLARE @tb TABLE([字段1] int, [字段2] nvarchar(10))
INSERT INTO @tb
SELECT 1, N '管理 '
UNION ALL SELECT 2, N '其他 '
UNION ALL SELECT 3, N '管理 '
UNION ALL SELECT 4, N '管理 '
UNION ALL SELECT 5, N '其他 '
UNION ALL SELECT 6, N '管理 '
UNION ALL SELECT 7, N '管理 '
UPDATE T
SET 字段2 = 字段2 + (SELECT CAST(COUNT(1) + 1 AS NVARCHAR) FROM @tb WHERE 字段2 = T.字段2 AND 字段1 < T.字段1)
FROM @tb T
select * from @tb
/*结果字段1 字段2
----------- ----------
1 管理1
2 其他1
3 管理2
4 管理3
5 其他2
6 管理4
7 管理5
*/
[解决办法]
create table T(字段1 int,字段2 varchar(10))
insert T select 1, '管理 '
union all select 2, '其他 '
union all select 3, '管理 '
union all select 4, '管理 '
union all select 5, '其他 '
union all select 6, '管理 '
union all select 7, '管理 '
union all select 8, '什么 '
update T set 字段2=字段2+rtrim((select count(*)+1 from T where 字段2=a.字段2 and 字段1 <a.字段1))
from T a
where exists(select 1 from T where 字段2=a.字段2 and 字段1 <> a.字段1)
select * from T
drop table T
--结果
字段1 字段2
----------- ----------
1 管理1
2 其他1
3 管理2
4 管理3
5 其他2
6 管理4
7 管理5
8 什么
(所影响的行数为 8 行)
[解决办法]
--总是比别人慢
create table tab(字段1 int, 字段2 varchar(20))
insert tab select 1, '管理 '
union all select 2, '其他 '
union all select 3, '管理 '
union all select 4, '管理 '
union all select 5, '其他 '
union all select 6, '管理 '
union all select 7, '管理 '
update tab set 字段2=字段2+RTRIM(cast((select count(1) from tab b where a.字段2=b.字段2 and a.字段1> =b.字段1)as char(5)))
from tab a
select * from tab
--
/*
1管理1
2其他1
3管理2
4管理3
5其他2
6管理4
7管理5
*/
[解决办法]
drop table #temp
Create table #temp
(
id int,
name varchar(20)
)
delete #temp
insert into #temp values(1, 'management ')
insert into #temp values(2, 'other ')
insert into #temp values(3, 'management ')
insert into #temp values(4, 'management ')
insert into #temp values(5, 'other ')
insert into #temp values(6, 'management ')
insert into #temp values(7, 'management ')
update #temp
set name=name+convert(varchar(2),(select count(*)+1 from #temp where name=a.name and id <a.id))
from #temp a
select * from #temp