日期:2014-05-18 浏览次数:20861 次
id ino_id ccode md mc ccode_equal 1 1 1001 10 0 1131 2 1 1131 0 10 1001 3 2 1001 100 0 1131,1130,1151 4 2 1131 0 40 1001 5 2 1130 0 50 1001 6 2 1151 0 10 1001 7 3 1001 100 0 1131,1121 8 3 1131 0 50 1001 9 3 1121 0 50 1001 10 4 1001 0 100 1131,1121 11 4 1131 50 0 1001 12 4 1131 30 0 1001 13 4 1121 20 0 1001
--> 测试数据:[test]
if object_id('[test]') is not null
drop table [test]
create table [test](
[id] int,
[ino_id] int,
[ccode] int,
[md] int,
[mc] int,
[ccode_equal] varchar(20)
)
go
insert [test]
select 1,1,1001,10,0,1131 union all
select 2,1,1131,0,10,1001 union all
select 3,2,1001,100,0,1131 union all
select 4,2,1131,0,40,1001 union all
select 5,2,1130,0,50,1001 union all
select 6,2,1151,0,10,1001 union all
select 7,3,1001,100,0,1131 union all
select 8,3,1131,0,50,1001 union all
select 9,3,1121,0,50,1001 union all
select 10,4,1001,0,100,1131 union all
select 11,4,1131,50,0,1001 union all
select 12,4,1131,30,0,1001 union all
select 13,4,1121,20,0,1001
go
with t
as(
select px=ROW_NUMBER()over(partition by [ino_id] order by getdate()),
* from test
),
m
as(
select
px=row_number()over(partition by ino_id order by getdate()),
ino_id,
right(N.[ccode],len(N.[ccode])-CHARINDEX(',',N.[ccode])) [ccode_equal]
from
(
select distinct
[ino_id]
from
test
)A
outer apply(
select distinct
[ccode]= STUFF(REPLACE(REPLACE(
(select
distinct [ccode] from test N
where ino_id = A.ino_id
for xml auto
),'<N ccode="', ','), '"/>', ''), 1, 1, '')
)N
)
select
t.id,t.ino_id,t.ccode,t.md,t.mc,
case when t.px=1 then m.ccode_equal else t.ccode_equal end as ccode_equal
from t
left join m
on t.px=m.px and t.ino_id=m.ino_id
/*
id ino_id ccode md mc ccode_equal
-------------------------------------------------
1 1 1001 10 0 1131
2 1 1131 0 10 1001
3 2 1001 100 0 1130,1131,1151
4 2 1131 0 40 1001
5 2 1130 0 50 1001
6 2 1151 0 10 1001
7 3 1001 100 0 1121,1131
8 3 1131 0 50 1001
9 3 1121 0 50 1001
10 4 1001 0 100 1121,1131
11 4 1131 50 0 1001
12 4 1131 30 0 1001
13 4 1121 20 0 1001
*/
------解决方案--------------------
一个语句搞定
SELECT id,ino_id,ccode,md,mc,
STUFF(REPLACE(REPLACE((SELECT ccode
FROM #t b
WHERE b.ino_id=a.ino_id
(CASE WHEN a.md=0 THEN b.mc ELSE b.md END)=0
FOR XML AUTO
),'<b ccode="', ','), '"/>', ''),1,1,'') ccode_equal
FROM #t a
------解决方案--------------------
sql2000用函数
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] int,[ino_id] int,[ccode] int,[md] int,[mc] int,[ccode_equal] varchar(14))
insert [tb]
select 1,1,1001,10,0,null union all
select 2,1,1131,0,10,null union all
select 3,2,1001,100,0,null union all
select 4,2,113