ControllerNo | VideoNo |
1 | 1 |
2 | 1 |
3 | 1 |
4 | 1 |
1 | 2 |
2 | 2 |
3 | 2 |
4 | 2 |
2 | 3 |
4 | 3 |
ControllerNoList | VideoNo |
1,2,3,4 | 1 |
1,2,3,4 | 2 |
0,2,0,4 | 3 |
--1.先行变列
select VideoNo,
ControllerNo1=max(case ControllerNo when 1 then ControllerNo else 0 end),
ControllerNo2=max(case ControllerNo when 2 then ControllerNo else 0 end),
ControllerNo3=max(case ControllerNo when 3 then ControllerNo else 0 end),
ControllerNo4=max(case ControllerNo when 4 then ControllerNo else 0 end)
from tb
group by VideoNo
执行结果:
VideoNo ControllerNo1 ControllerNo2 ControllerNo3 ControllerNo4
----------- ------------- ------------- ------------- -------------
1 1 2 3 4
2 1 2 3 4
3 0 2 0 4
(所影响的行数为 3 行)
--2.对上图所产生的表t进行“合并多列为一列”操作
select cast(ControllerNo1 as varchar)+','+cast(ControllerNo2 as varchar)+','+cast(ControllerNo3 as varchar)+','+cast(ControllerNo4 as varchar) as ControlerNoList,
VideoNo from t
★全部sql语句如下★
create table tb
(
ControllerNo int not null,
VideoNo int not null)
insert into tb (ControllerNo,VideoNo) values (1,1)
insert into tb (ControllerNo,VideoNo) values (2,1)
insert into tb (ControllerNo,VideoNo) values (3,1)
insert into tb (ControllerNo,VideoNo) values (4,1)
insert into tb (ControllerNo,VideoNo) values (1,2)
insert into tb (ControllerNo,VideoNo) values (2,2)
insert into tb (ControllerNo,VideoNo) values (3,2)
insert into tb (ControllerNo,VideoNo) values (4,2)
insert into tb (ControllerNo,VideoNo) values (2,3)
insert into tb (ControllerNo,VideoNo) values (4,3)
select*from tb
select cast(ControllerNo1 as varchar)+','+cast(ControllerNo2 as varchar)+','+cast(ControllerNo3 as varchar)+','+cast(ControllerNo4 as varchar) as ControlerNoList,
VideoNo from
(select VideoNo,
ControllerNo1=max(case ControllerNo when 1 then ControllerNo else 0 end),
ControllerNo2=max(case ControllerNo when 2 then ControllerNo else 0 end),
ControllerNo3=max(case ControllerNo when 3 then ControllerNo else 0 end),
ControllerNo4=max(case ControllerNo when 4 then ControllerNo else 0 end)
from tb
group by VideoNo) t
执行结果为:
★可将sql语句更新为:
select (case ControllerNo1 when 0 then '' else cast(ControllerNo1 as varchar)+',' end)
+(case ControllerNo2 when 0 then '' else cast(ControllerNo2 as varchar)+',' end)
+(case ControllerNo3 when 0 then '' else cast(ControllerNo3 as varchar)+',' end)
+(case ControllerNo4 when 0 then '' else cast(ControllerNo4 as varchar) end)
as ControlerNoList,
VideoNo from
(select VideoNo,
ControllerNo1=max(case ControllerNo when 1 then ControllerNo else 0 end),
ControllerNo2=max(case ControllerNo when 2 then ControllerNo else 0 end),
ControllerNo3=max(case ControllerNo when 3 then ControllerNo else 0 end),
ControllerNo4=max(case ControllerNo when 4 then ControllerNo else 0 end)
from tb
group by VideoNo) t
查询效果如下: