日期作为SQL Server中的别名

时间:2015-04-20 20:53:50

标签: sql-server sql-server-2012

我试图将几列列为日期值,并尝试不同的方法。

SELECT  
   r.RET_MAIN_DSC,
   max(case when day_dt=Convert(date, getdate()-7) and EXT_SALES_AMT2>0 then 'X' else '-' end) as a,
   max(case when day_dt=Convert(date, getdate()-6) and EXT_SALES_AMT2>0 then 'X' else '-' end) as b,
   max(case when day_dt=Convert(date, getdate()-5) and EXT_SALES_AMT2>0 then 'X' else '-' end) as c,
   max(case when day_dt=Convert(date, getdate()-4) and EXT_SALES_AMT2>0 then  'X' else '-' end) as d,
   max(case when day_dt=Convert(date, getdate()-3) and EXT_SALES_AMT2>0 then 'X' else '-' end) as e,
   max(case when day_dt=Convert(date, getdate()-2) and EXT_SALES_AMT2>0 then 'X' else '-'  end) as f,
   max(case when day_dt=Convert(date, getdate()-1) and EXT_SALES_AMT2>0 then 'X'  else '-' end) as g,
   max(case when day_dt=Convert(date, getdate()) and EXT_SALES_AMT2>0 then 'X' else '-' end) as h
FROM 
    GNL_STR_POS_ACT_1000_F POS
JOIN 
    VC_RET_COUNTRY RET ON POS.RET_COUNTRY_ID = RET.RET_COUNTRY_ID
JOIN 
    VC_RETAILER r on r.RET_ID=ret.RET_ID
WHERE 
    DAY_DT BETWEEN GETDATE() - 8 AND GETDATE()
GROUP BY  
    r.RET_MAIN_DSC

我正在尝试将每个列别名为day_dt值。

例如,对于列名称,别名必须为getdate()-7

有人可以帮助我吗?

由于

1 个答案:

答案 0 :(得分:2)

你需要使用Dynamic sql,就像这样......

DECLARE @Sql NVARCHAR(MAX);

SET @Sql = N' SELECT  r.RET_MAIN_DSC,
max(case when day_dt=Convert(date, getdate()-7) and EXT_SALES_AMT2>0 then ''X'' else ''-'' end) as '+ QUOTENAME(CONVERT(VARCHAR(10), GETDATE()-7, 120)) +',
max(case when day_dt=Convert(date, getdate()-6) and EXT_SALES_AMT2>0 then ''X'' else ''-'' end) as '+ QUOTENAME(CONVERT(VARCHAR(10), GETDATE()-6, 120)) +',
max(case when day_dt=Convert(date, getdate()-5) and EXT_SALES_AMT2>0 then ''X'' else ''-'' end) as '+ QUOTENAME(CONVERT(VARCHAR(10), GETDATE()-5, 120)) +',
max(case when day_dt=Convert(date, getdate()-4) and EXT_SALES_AMT2>0 then ''X'' else ''-'' end) as '+ QUOTENAME(CONVERT(VARCHAR(10), GETDATE()-4, 120)) +',
max(case when day_dt=Convert(date, getdate()-3) and EXT_SALES_AMT2>0 then ''X'' else ''-'' end) as '+ QUOTENAME(CONVERT(VARCHAR(10), GETDATE()-3, 120)) +',
max(case when day_dt=Convert(date, getdate()-2) and EXT_SALES_AMT2>0 then ''X'' else ''-'' end) as '+ QUOTENAME(CONVERT(VARCHAR(10), GETDATE()-2, 120)) +',
max(case when day_dt=Convert(date, getdate()-1) and EXT_SALES_AMT2>0 then ''X'' else ''-'' end) as '+ QUOTENAME(CONVERT(VARCHAR(10), GETDATE()-1, 120)) +',
max(case when day_dt=Convert(date, getdate()) and EXT_SALES_AMT2>0 then ''X'' else ''-'' end)   as '+ QUOTENAME(CONVERT(VARCHAR(10), GETDATE(), 120)) +'
 FROM GNL_STR_POS_ACT_1000_F POS
JOIN VC_RET_COUNTRY RET ON POS.RET_COUNTRY_ID = RET.RET_COUNTRY_ID
join VC_RETAILER r on r.RET_ID=ret.RET_ID
WHERE DAY_DT BETWEEN GETDATE()-8 AND GETDATE()
GROUP BY  r.RET_MAIN_DSC'

Exec sp_executesql @sql