How to rename the header of column 'Q1_2022 to parameter @filteredDate. Below is the working query but don't know how to rename the header '03-31-2022' using @filteredDate. Please suggest.
declare @filteredDate Date = '03-31-2022'
select *
from
(SELECT 'BSA' as tabs, ' xyz' as Type, ColumnName AS 'Report',
ColumnValue AS 'Q1_2022'
FROM
(
SELECT
SUM(CAST(col1 AS BIGINT)) AS col1_,
SUM(CAST(col2 AS BIGINT)) AS col2_
FROM [dbo].[table1] table1
FULL OUTER JOIN [dbo].[table2] table2 ON table1.ID = table2.ID
WHERE table5.Institution = '100_bank'
and FileDate = @filteredDate
) p
UNPIVOT
(
ColumnValue FOR ColumnName IN (col1_ , col2_)) unpiv);
1条答案
按热度按时间pengsaosao1#
There is no way to use dynamic column name at run time, you have to use dynamic sql query, the idea is first you create the query and then execute it like this:
SQL Fiddle
You can read more about dynamic query here: https://www.sqlshack.com/dynamic-sql-in-sql-server/