Please find sample input tables named as Table1 and Table2.
Table1 :
| id | Dates | Sales |
| ------------ | ------------ | ------------ |
| 1 | 18 Sept'23 | 445.23 |
| 1 | 20 Sept'23 | 470.33 |
| 1 | 22 Sept'23 | 500.33 |
Table2 :
id | Dates |
---|---|
1 | 18 Sept'23 |
1 | 19 Sept'23 |
1 | 20 Sept'23 |
1 | 21 Sept'23 |
1 | 22 Sept'23 |
1 | 23 Sept'23 |
1 | 24 Sept'23 |
Desired output :
id | 18 Sept'23 | 19 Sept'23 | 20 Sept'23 | 21 Sept'23 | 22 Sept'23 | 23 Sept'23 | 24 Sept'23 |
---|---|---|---|---|---|---|---|
1 | 445.23 | N/A | 470.33 | N/A | 500.33 | N/A | N/A |
Declare @PvtQry nvarchar(max)
Declare @Qry nvarchar(max)
SELECT @PvtQry = COALESCE(@PvtQry+',','') + QUOTENAME([Dates]) FROM Table2 WHERE id = 1 Order by Dates Desc
Set @Qry = 'Select id,'+@PvtQry+' INTO ##Tbl_Temp
FROM (Select id,Dates,Sales as SalesValue FROM Table1) AS Source
PIVOT (Max (isnull(Cast(SalesValue as nvarchar(100)),''N/A'') FOR [Dates] IN ('+@PvtQry+') AS Pvt'
EXEC sp_executesql @Qry
SELECT * FROM ##Tbl_Temp
Error Message: Msg 102, Level 15, State 1, Line 3 Incorrect syntax near '('.
1条答案
按热度按时间c9qzyr3d1#
The T-SQL generated in
@qry
is not valid, so I refactored it to work.I moved the code to insert
N/A
from thePIVOT
to theSELECT
clause, the following is a sample query.To generate this code dynamically you need to use an additional variable to use in the
SELECT
clause, that cast the sales value to a string and manage the null value, in the following way: