我正在使用SQL Server 2014.我正在使用一个返回表的存储过程。
我们有两个输入参数,@ from和@until,它们定义了我们将要搜索的日期范围的开始和结束。
在查询结束时,我们使用PIVOT将列转换为行。
我能够正确地选择数据,但是在PIVOT之后有一个问题: 许多列完全返回NULL,因为它们不包含在@from和@until设置的日期范围内。
我可以做什么,以至于我根本没有获得NULL
列?
这是我的代码:
ALTER PROCEDURE [dbo].[presupuestosVenta]
@from char(8), (in this case 201501)
@until char(8) (in this case 201506)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @venta TABLE
(
LAPSO_DOC CHAR(6),
ID_EXT_ITM CHAR(3),
ID_TALLA CHAR(6),
VENTA INT
)
INSERT INTO @venta
SELECT
LAPSO_DOC,
ID_EXT_ITM,
ID_TALLA,
CAST (CANTIDAD_CAP AS INT) AS VENTA
FROM dbo.a_presupuestosVenta
WHERE
( ID_REFER = '312177000'
OR ID_REFER = '314001000'
OR ID_REFER = '315099000'
)
AND LAPSO_DOC BETWEEN @from AND @until
SELECT *
FROM @venta
PIVOT
(
SUM(VENTA)
FOR LAPSO_DOC
IN ([201501],[201502], [201503], [201504],[201505], [201506] )
)
AS PivotTable
ORDER BY ID_EXT_ITM DESC, ID_TALLA ASC
END
以下是我得到的结果:
编辑:我一直在研究DYNAMIC PIVOT QUERY,但是一直有错误说我的桌子@venta没有定义: DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);
SET @columns = N'';
SELECT @columns += N', v.' + QUOTENAME(LAPSO_DOC)
FROM (SELECT v.LAPSO_DOC FROM @venta AS v
GROUP BY v.LAPSO_DOC) AS x;
SET @sql = N'
SELECT ' + STUFF(@columns, 1, 2, '') + '
FROM
(
SELECT v.VENTA, v.LAPSO_DOC
FROM @venta as v
) AS j
PIVOT
(
SUM(VENTA) FOR LAPSO_DOC IN ('
+ STUFF(REPLACE(@columns, ', v.[', ',['), 1, 1, '')
+ ')
) AS v;';
PRINT @sql;
EXEC sp_executesql @sql;
答案 0 :(得分:1)