I have these two tables:
Table A
pj item desc pj_id
------------------------------------
pjA iphone cell phone 1
pjA macbook laptop 2
pjB windows os 3
Table B
pj item pj_id version date
-----------------------------------------
pjA iphone 1 2 2010
pjA iphone 1 3 2011
pjA macbook 2 0 2000
pjB windows 3 5 2008
pjB windows 3 6 2014
pjB windows 3 7 2017
And I want
pj item desc detail1 detail2 detail3
---------------------------------------------------------
pjA iphone cell phone 2010(2) 2011(3)
pjA macbook laptop 2000(0)
pjB windows os 2008(5) 2014(6) 2017(7)
You can see the column "detail" is dynamic, because there are no fix numbers of version of an item in table B
As we know, PIVOT
or FOR XML PATH
aren't supported on SQL Server 2000.
So I googled some solutions but they usually use stored procedure or function, but I don't have the permissions on this database.
The closest answer for me probably is this , but I have no idea how to use on my table.
Any help would be appreciated.
I have a solution. You can use a temp table to create the 'Details' with a RowNum column and then Pj_id grouped. And by using a left join, you can bring the 'Details' back in. I have only done for 3 'Details'. You can expand as you wish.
declare @tableA table(pj varchar(20), item varchar(50), descb varchar(100), pj_id int)
insert into @tableA
select 'pjA', 'iphone', 'cell phone', 1 union all
select 'pjA', 'macbook', 'laptop', 2 union all
select 'pjB', 'windows', 'os', 3
declare @tableB table(pj varchar(20), item varchar(50), pj_id int, version int, vdate int)
insert into @tableB
select 'pjA', 'iphone', 1, 2, 2010 union all
select 'pjA', 'iphone', 1, 3, 2011 union all
select 'pjA', 'macbook', 2, 0, 2000 union all
select 'pjB', 'windows ', 3, 5, 2008 union all
select 'pjB', 'windows', 3, 6, 2014 union all
select 'pjB', 'windows',3, 7, 2017
declare @Details table(pj_id int, Detail varchar(100), RowNum int)----IDENTITY(1,1)
insert into @Details
SELECT pj_id,
Detail=cast(vdate as varchar(20))+'('+cast(SUM(version) as varchar(20))+')',
RowNum = (SELECT COUNT(*) ---Simulating Row_num here
FROM @tableB i
WHERE i.pj_id = o.pj_id
AND cast(i.vdate as varchar(20))<=cast(o.vdate as varchar(20)) )
FROM @tableB o
group by
pj_id, cast(o.vdate as varchar(20))
ORDER BY pj_id, Detail
select
A.*,
detail1=D1.Detail,
detail2=D2.Detail,
detail3=D3.Detail
from
@tableA A
left join @Details D1 ON
D1.pj_id=A.pj_id
AND
D1.RowNum=1
left join @Details D2 ON
D2.pj_id=A.pj_id
AND
D2.RowNum=2
left join @Details D3 ON
D3.pj_id=A.pj_id
AND
D3.RowNum=3
I have simulated ROW_NUMBER.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.