Tuesday, March 27, 2007

Transpose sql

declare @MaxDebtNr integer
select @MaxDebtNr = max(cnt) from (select name, count(*) cnt from MyTable group by Name) x
declare @MySQL varchar(8000)
set @MySQL = 'select name'
declare @i integer
set @i = 1
while @i <= @MaxDebtNr begin set @MySQL = @MySQL + ',max(case when DebtNr = ' + cast(@i as varchar(3)) + ' then DebtID end) as DebtID' + cast(@i as varchar(3)) set @i = @i + 1 end set @MySQL = @MySQL + ' from (select a.Name, a.DebtID, count(*) DebtNr from MyTable a join MyTable b on a.Name = b.Name and a.DebtID >= b.DebtID
group by a.Name, a.DebtID
) sub group by name'
exec (@MySQL)
SELECT LIPQOH,* FROM PRODDTA.F41021 WHERE LIPQOH>0 AND LIITM>1500000
select sdso02,sdnxtr,sdlttr,* from proddta.f4211 where sddoco=389665 and sdlitm='1606018'
F98950
ALTER PROCEDURE [DBO].[SCOWNEREP]
@Itno as varchar(25)='1609463'
AS
select
' '+rtrim(CICMPID)+'' "Certificate No",
citno "Item No",CIOWNO "Owner No",CISHDT "Ship Date",CIPRDCTR "Prod Ctr" ,
CIAMRNO1 AMD1, CIAMRCM1 "AMD Com" ,CIAMRNO2 AMD2, CIAMRCM2 "AMD Com",CIAMRNO3 AMD3, CIAMRCM3 "AMD Com",
CIAMRNO4 AMD4, CIAMRCM4 "AMD Com",CIAMRNO5 AMD5, CIAMRCM5 "AMD Com",CICMPID
from jde_rk.dbo.SCCERINFODET where citno=@Itno
GO

No comments: