我有一些数据,我需要支点(我相信),并阅读了许多关于如何做到这一点的文章。我甚至实现了一个有助于处理动态列(这是我需要的)的方法,但是,我只能得到一个字段来填充最终结果。
这是我当前的结果集,在旋转之前:
这是期望的结果(在pivot或其他什么之后):
我的基本查询是:
SELECT
(SELECT Value FROM dbo.ParseDelimetedString(st.CMA_CODE, 1, default)) + '-' + (SELECT Value FROM dbo.ParseDelimetedString(st.CMA_CODE, 2, default)) AS ACCNumber,
(SELECT Value FROM dbo.ParseDelimetedString(st.CMA_CODE, 3, default)) AS Modification,
OS_NUMBER,
VIS_GRADE
FROM
SupportingEngineTest AS st
WHERE
FINAL_FORMULA_ID = 9477
我现在的动态轴心是:
DECLARE @Columns AS VARCHAR(MAX)
SELECT @Columns = COALESCE(@Columns + ', ', '') + QUOTENAME(ACCNumber)
FROM (
-- Distinct ACC Numbers
SELECT DISTINCT
(SELECT Value FROM dbo.ParseDelimetedString(st.CMA_CODE, 1, default)) + '-' + (SELECT Value FROM dbo.ParseDelimetedString(st.CMA_CODE, 2, default)) AS ACCNumber
FROM
SupportingEngineTest AS st
WHERE
FINAL_FORMULA_ID = 9477
) AS Distincts
ORDER BY
Distincts.ACCNumber
DECLARE @SQL AS VARCHAR(MAX)
SET @SQL = 'SELECT Modification, ' + @Columns + '
FROM (
SELECT
ROW_NUMBER() OVER(ORDER BY st.CMA_CODE ASC) AS RowNumber,
st.CMA_CODE,
(SELECT Value FROM dbo.ParseDelimetedString(st.CMA_CODE, 1, default)) + ''-'' + (SELECT Value FROM dbo.ParseDelimetedString(st.CMA_CODE, 2, default)) AS ACCNumber,
(SELECT Value FROM dbo.ParseDelimetedString(st.CMA_CODE, 3, default)) AS Modification,
OS_NUMBER,
VIS_GRADE
FROM
SupportingEngineTest AS st
WHERE
FINAL_FORMULA_ID = 9477
) AS PivotData
PIVOT (
MIN(RowNumber)
FOR ACCNumber IN (' + @Columns + ')
) AS PivotRessult
ORDER BY
Modification'
EXEC(@SQL)
输出为:
我添加了 RowNumber
以及 CMA_CODE
我可以集中精力,但都没用。我用过 ACCNumber
在聚合中,并确保它向我显示该值,但我不确定如何让其他每个字段都显示在结果中。
暂无答案!
目前还没有任何答案,快来回答吧!