I have a table ProductTransDetailPassenger the structure is
PID FirstName Email Phone NoOfAdult NoOfChild
1 ABC [email protected] 111 2 0
1 XYZ [email protected] 222 2 0
2 QWE [email protected] 333 2 1
2 RTY [email protected] 444 2 1
2 YUI [email protected] 555 2 1
Based on the traveler Count(i.e No.OfAdult + No.OfChild) I need to display the result as
PID FirstName-1 Email-1 Phone-1 FirstName-2 Email-2 Phone-2 FirstName-3 Email-3 Phone-3
1 ABC [email protected] 111 XYZ [email protected] 222 N/A N/A N/A
2 QWE [email protected] 333 RTY [email protected] 444 YUI [email protected] 555
The table may change dynamically according to the max number of travelers. For an PID with less number of travelers than the Max, the remaining columns need to be displayed as N/A
Can u please help me out with this!!
I have tried this implementation using the PIVOT, but the result is not as expected
Thanks in Advance,
The SQL Snippet
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SET @cols = STUFF((SELECT distinct + char(10) + QUOTENAME(PTDP.FirstName) --+ QUOTENAME(AP.Type) + QUOTENAME(PTDP.EmailAddress) + QUOTENAME(PTDP.PhoneNumber) + QUOTENAME(DAY(GETDATE() - PTDP.Birthdate))
FROM ProductTransactionDetailPassenger PTDP
INNER JOIN AppParameters AP ON AP.EnumValue = PTDP.GenderTypeValue AND Ap.Context = 'Gender'
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @query = N'SELECT ' + @cols + ' from
(
select
PTDP.ProductTransactionDetailID PID,
PTDE.ProductTransactionDetailID ID
from ProductTransactionDetailPassenger PTDP
inner join ProductTransactionDetail PTD
on PTD.ProductTransactionDetailID=PTDP.ProductTransactionDetailID
and PTD.ParentProductTransactionDetailID=00000000-0000-0000-0000-000000000000
INNER JOIN dbo.ProductTransactionDetailExtended PTDE ON PTDE.ProductTransactionDetailID = PTD.ProductTransactionDetailID
) x
pivot
(
max(x.PID) //this must be traveler count
for ' + @cols + ' in (' + @cols + ')
) p '
print @query
execute(@query)
The query below should get you the desired results: