我想显示24个月的数据(按月命名),但是如查询中所示,我必须为每个月输入24列,这会使查询变长。
DECLARE @sql NVARCHAR(MAX) = 'SELECT [STORE] = ET_LIBELLE,
CONVERT(DECIMAL(15,0),SUM(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())) + ',
CONVERT(DECIMAL(15,0),SUM(CASE WHEN YEAR(GP_DATEPIECE) = YEAR(DATEADD(MONTH,-2,GETDATE()))
AND month(GP_DATEPIECE) = MONTH( DATEADD(MONTH,-2,GETDATE()))
THEN ISNULL([SALES], 0) ELSE 0 END)) AS ' + DATENAME(MONTH, DATEADD(MM,-2, GETDATE())) + ',
.
.
.
FROM PIECE
GROUP BY ET_LIBELLE'
EXEC sp_executesql @sql
结果:
STORE - April - March - February - ..
--------------------------------------------------------
S1 - 5500 - 6530 - 4550 - ..
S2 - 2400 - 8740 - 9650 - ..
..
--------------------------------------------------------
请问有什么优化和快速查询的解决方案吗?
答案 0 :(得分:0)
以下脚本将按12个月(JAN到DEC)返回数据,但每年返回1行。如果可以接受,则可以使用此查询。您还可以设置要选择多少个月的月份数(@HowManyMonth = N)。
DECLARE @HowManyMonth INT
SET @HowManyMonth = 24
DECLARE @StartDate DATE
SET @StartDate = CAST(DATEADD(DD,-(DAY(DATEADD(MM,-(@HowManyMonth-1),GETDATE()))-1),DATEADD(MM,-(@HowManyMonth-1),GETDATE())) AS DATE)
SELECT * FROM
(
SELECT Store,Sales,
YEAR(GP_DATEPIECE) YR,
CASE MONTH(GP_DATEPIECE)
WHEN 1 THEN 'JAN' WHEN 2 THEN 'FEB' WHEN 3 THEN 'MAR' WHEN 4 THEN 'APR' WHEN 5 THEN 'MAY' WHEN 6 THEN 'JUN'
WHEN 7 THEN 'JUL' WHEN 8 THEN 'AUG' WHEN 9 THEN 'SEP' WHEN 10 THEN 'OCT' WHEN 11 THEN 'NOV' WHEN 12 THEN 'DEC'
END MONTH
FROM PIECE
WHERE GP_DATEPIECE >= @StartDate
)AS P
PIVOT
(
SUM(Sales)
FOR MONTH IN ([JAN],[FEB],[MAR],[APR],[MAY],[JUN],[JUL],[AUG],[SEP],[OCT],[NOV],[DEC])
) PVT