I am working on some projects and suppose I have a table with a column called Date
. Now I want to create a new table, with MAX(Date)
and its 5 previous months to be my columns.
For example, suppose
MAX(Date) = '2023-05-01'
in my original table, then I want the columns in my new table to be
'2022-12-01', ..., '2023-04-01', '2023-05-01'
which are 6 columns. And I want this script can work for any MAX(Date)
, like whatever data I got, I can use this script to get a new table with 6 previous months to be the columns.
I am confused as to how to create this new table for any Date
. If anyone has any idea, very appreciated and thanks!
I've tried some dynamic SQL but it seems no work. And I am not quite understand how it can work when creating a new table.
1条答案
按热度按时间6ie5vjzr1#
Ignoring the most important point of should you do this...
Setting up some test data:
As you alluded to, you could use some Dynamic SQL to achieve this:
This results in a table being created as you wish, with the following SQL command for this particular example data: