1、静态SQL语句(适合"加工类型"类固定的情况):
------------------------------------------------------------------
select
模号 = a.MoldId,
工件 = a.WorkpieceId,
铜公 = a.CopperId,
爆公数量 = a.BurstCopper,
粗公数量 = a.RoughCopper,
幼公数量 = a.ChildrenCopper,
CNC = max(case b.ProcessType when 'CNC' then State end),
车床 = max(case b.ProcessType when '车床' then State end),
铣床 = max(case b.ProcessType when '铣床' then State end),
线切割 = max(case b.ProcessType when '线切割' then State end),
雕刻 = max(case b.ProcessType when '雕刻' then State end),
执模 = max(case b.ProcessType when '执模' then State end),
EDM = max(case b.ProcessType when 'EDM' then State end)
from
Coppers a
inner join
Processes b
on
a.MoldId = b.MoldId
group by
a.MoldId,a.WorkpieceId,a.CopperId,
a.BurstCopper,a.RoughCopper,a.ChildrenCopper
2、动态SQL语句(适合"加工类型"类不固定的情况):
------------------------------------------------------------------
declare @s varchar(8000)
set @s = ''
select
@s = @s + ','+ProcessType
+ '=max(case b.ProcessType when '''+ ProcessType+''' then State end)'
from
Processes
group by
ProcessType
set @s = 'select 模号 = a.MoldId,'
+' 工件 = a.WorkpieceId,'
+' 铜公 = a.CopperId,'
+' 爆公数量 = a.BurstCopper,'
+' 粗公数量 = a.RoughCopper,'
+' 幼公数量 = a.ChildrenCopper'
+ @s
+' from Coppers a inner join Processes b on a.MoldId = b.MoldId'
+' group by a.MoldId,a.WorkpieceId,a.CopperId'
+' ,a.BurstCopper,a.RoughCopper,a.ChildrenCopper'
exec(@s)
/*引用*/
1.包含两个表------典型行列转换问题例子
--建立测试环境
create table tb1 (id nvarchar(10),type nvarchar(10))
insert into tb1 select '11','a' union all select '22','b' union all select '33','c'
create table tb2 (n int,type nvarchar(10),num int)
insert into tb2 select '1','11','4' union all select '1','11','5'
union all select '2','22','8' union all select '3','22','5'
--查询处理
DECLARE @SQL VARCHAR(8000)
SET @SQL='select n '
SELECT @SQL= @SQL+',sum(case when type='+ttt+' then num else 0 end)['+tt+']' from
(select distinct a.type as tt,isnull(b.type,'0') as ttt from tb2 b right join tb1 a on a.id=b.type) b
set @sql=@sql+' from tb2 group by n'
print @sql
exec(@sql)
go--删除测试环境
Drop Table tb1,tb2
create table roy(a int,b varchar(10),c int,d int)
insert roy
select 1, '小李', 1, 2 union all
select 2, '小王', 4, 5 union all
select 1, '小李', 3, 4 union all
select 2, '小王', 6, 7 union all
select 1, '小李', 5, 6 union all
select 2, '小王', 8, 9
begin TRANSACTION
select * ,d=1 into roy1
from (select a,b,c from roy
union all
select a,b,d from roy)a order by b,c asc--排序方式
declare @a int
set @a=0
update roy1
set d=@a,@a=@a+1
select a,b,c,d=(select count(*)from roy1 where a=a.a and d!>a.d )into roy2
from roy1 a
declare @s varchar(1000)
set @s=''
select @s=@s+',['+convert(varchar,d)+']=sum(case d when '''+convert(varchar,d)+'''then c else '''' end)'
from roy2 group by d
set @s='select a,b'+@s+ 'from roy2 group by a,b'
exec (@s)
ROLLBACK TRANSACTION