根据WHERE条件动态命名列

时间:2019-02-18 22:31:57

标签: sql sql-server tsql dynamic

目标:

我每周运行一次查询,希望其中一列返回带有前缀“ W”的ISO_WEEK数字。例如:W1。

更具体地说,我想将以下条件重现为列名。

DATEPART(ISO_WEEK, table.login) = DATEPART(ISO_WEEK,GETDATE())-2

主要查询是:

 SELECT 
     CAST(t.log_time as Date)           AS Week1
    ,DATEPART(ISO_WEEK,t.log_time)      AS Week_Number -- Dynamically named with ISO_WEEK
    ,email                              AS Emails
 FROM table.memberlog as t
 WHERE 1=1
    AND DATEPART(ISO_WEEK, t.log_time) = DATEPART(ISO_WEEK,GETDATE())-2
    AND DATEPART(YEAR, t.log_time) = DATEPART(YEAR,GETDATE())

1 个答案:

答案 0 :(得分:1)

SQL Server在设计上是声明性的,不支持宏替换。这样就留下了动态SQL,例如...

Declare @SQL varchar(max) = '
SELECT 
     CAST(t.log_time as Date)           AS Week1
    ,DATEPART(ISO_WEEK,t.log_time)      AS '+concat('W',DATEPART(ISO_WEEK,GETDATE())-2)+'
    ,email                              AS Emails
 FROM table.memberlog as t
 WHERE 1=1
    AND DATEPART(ISO_WEEK, t.log_time) = DATEPART(ISO_WEEK,GETDATE())-2
    AND DATEPART(YEAR, t.log_time) = DATEPART(YEAR,GETDATE())
'

Exec(@SQL)