我想在 Sql Server 中显示行到列。我已经看到了其他问题,但这些列在数据透视表中是硬编码的,但我的列将是动态的。到目前为止我所取得的成就。如屏幕截图所示,我能够将行转换为列,但我无法完成的几件事..需要你的帮助
- 将所有列中的 NULL 替换为 0
- 需要再添加 1 列,它将显示除 companyID 之外的所有列的总和
我的 SQL 代码:
DECLARE @Columns VARCHAR(MAX)
DECLARE @Convert VARCHAR(MAX)
SELECT @Columns = STUFF((
SELECT '],[' + ErrClassfn
from ArchimedesTables.dbo.PM_ErrClassificationSetup
WHERE CONVERT(VARCHAR(10), ISNULL(EndDate, GETDATE()), 101)
Between CONVERT(VARCHAR(10), GETDATE(), 101)
AND CONVERT(VARCHAR(10), GETDATE(), 101)
ORDER BY '],[' + CONVERT(VARCHAR(MAX), ID) ASC
FOR
XML PATH('')
), 1, 2, '') + ']'
SET @Convert = 'SELECT * INTO #mynewTable FROM
(
SELECT COUNT(WQ.ErrClassfnID) as ErrorCount, UPPER(WQ.CompanyID) as CompanyID,
PME.ErrClassfn as ErrorName
FROM Version25.dbo.WF_Quality AS WQ
LEFT JOIN ArchimedesTables.dbo.PM_ErrClassificationSetup as PME
ON WQ.ErrClassfnID = PME.ID
GROUP BY
UPPER(CompanyID), ErrClassfn
) Quality PIVOT ( SUM(ErrorCount) For ErrorName IN (' + @Columns
+ ')) as PivotTable SeLeCt * FROM #mynewTable'
EXEC(@Convert)