'In TSQL How do I build a temp table with dynamic columns (or rows) based on row values from a query
What is the best way to build a temp tables with dynamic rows or columns - correspond to the row values of another query.
For example my query (this could change based on the user determination at any given moment)
SELECT ID, Description
FROM TableX
WHERE coded_value = 149 AND year = @year
will currently return values that appear as follows
| ID | Description |
|---|---|
| 1 | In Person |
| 2 | Hybrid |
| 3 | Virtual |
I would select the Description field from this table and want those values to appear as columns in another table.
Here is how my code is built
The other table is built as follows
CREATE TABLE #final_table
(
[Year] varchar(5),
month_name varchar(25),
[month] int,
Requested int,
Num_Requested int,
Booked int,
Num_Booked int,
Cancelled int,
Num_Cancelled int,
category, varchar(10)
)
;WITH months ([monthDate], [month]) AS
(
SELECT CAST(@Year + '-01-01' AS date), 1
UNION ALL
SELECT DATEADD(month, 1, [monthDate]), [month] + 1
FROM months
WHERE DATEADD(month, 1, [monthDate]) <= CASE WHEN @Year = YEAR(getdate()) THEN CAST(GETDATE() AS date) ELSE CAST(@Year + '-12-31' AS date) END
)
INSERT INTO #final_table (year, month_name, month)
SELECT
CONCAT('fy', SUBSTRING(CAST(Year AS varchar), 3, 2)) AS year,
DATENAME(month, [monthDate]) [monthDate],
[month]
FROM
months
This query returns the following: a row for each month and year (as a parameter the user provided @year).
My output currently looks like this
| MonthName | MonthID | Requested | Other Columns Etc | Category |
|---|---|---|---|---|
| January | 1 | NULL | ... | |
| February | 2 | NULL | ... | |
| March | 3 | NULL | ... | |
| April | 4 | NULL | ... |
What I want the output to look like
| A header | Another header | Requested | Other Columns | Category |
|---|---|---|---|---|
| January | 1 | NULL | ... | In - Person |
| January | 1 | NULL | ... | Hybrid |
| January | 1 | NULL | ... | Virtual |
| February | 2 | NULL | ... | In - Person |
| February | 2 | NULL | ... | Hybrid |
| February | 2 | NULL | ... | Virtual |
and so on
now alternatively I don't object to something like this either
| MonthName | MonthID | Requested In - Person | Requested Hybrid | Requested Virtual | Other Columns |
|---|---|---|---|---|---|
| January | 1 | NULL | ... | ||
| February | 2 | NULL | ... | ||
| March | 3 | NULL | ... | ||
| April | 4 | NULL | ... |
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
