如何获得前几个月的名字

时间:2019-05-20 10:35:17

标签: sql-server

我有这个查询,它返回前几个月的数据,例如[Month -1]。

Select [STORE] = ET_LIBELLE,

CASE WHEN YEAR(GP_DATEPIECE) = YEAR(DATEADD(MONTH,-1,GETDATE()))
AND  month(GP_DATEPIECE) =  MONTH( DATEADD(MONTH,-1,GETDATE()))
THEN ISNULL([SALES], 0) ELSE 0 END) AS [Month-1],

CASE WHEN YEAR(GP_DATEPIECE) = YEAR(DATEADD(MONTH,-1,GETDATE()))
AND  month(GP_DATEPIECE) =  MONTH( DATEADD(MONTH,-1,GETDATE()))
THEN ISNULL([SALES], 0) ELSE 0 END) AS [Month-2],

.
.
.

FROM PIECE
GROUP BY ET_LIBELLE

我需要的是在[月-1]内获取上一个月的名称,..

例如:当前月份为5月:

------------------------------------------
Store -  April - March - February - January
------------------------------------------
S1    -  2620  - 8955 -  6541   - 7410
------------------------------------------
S2    -  3620  - 5455 -  6852   - 4810
------------------------------------------

1 个答案:

答案 0 :(得分:3)

SELECT DATENAME(MONTH, DATEADD(MM,-1, GETDATE()))

要生成动态列名,请考虑使用动态SQL查询:

DECLARE @sql NVARCHAR(MAX) = 'SELECT 1 AS '+DATENAME(MONTH, DATEADD(MM,-1, GETDATE()))
EXEC sp_executesql @sql

结果

enter image description here

In your case: 
DECLARE @sql NVARCHAR(MAX) = 'Select [STORE] = ET_LIBELLE,

CASE WHEN YEAR(GP_DATEPIECE) = YEAR(DATEADD(MONTH,-1,GETDATE()))
AND  month(GP_DATEPIECE) =  MONTH( DATEADD(MONTH,-1,GETDATE()))
THEN ISNULL([SALES], 0) ELSE 0 END) AS ' + DATENAME(MONTH, DATEADD(MM,-1, GETDATE())) + ',

CASE WHEN YEAR(GP_DATEPIECE) = YEAR(DATEADD(MONTH,-1,GETDATE()))
AND  month(GP_DATEPIECE) =  MONTH( DATEADD(MONTH,-1,GETDATE()))
THEN ISNULL([SALES], 0) ELSE 0 END) AS ' + DATENAME(MONTH, DATEADD(MM,-2, GETDATE())) + ',

.
.
.

FROM PIECE
GROUP BY ET_LIBELLE'