我对SQL代码没有经验,所以去吧。
我想从表中提取数据,并使用PIVOT将值转换为列标题。
我已经设法使用PIVOT命令(和动态字段名称)实现了我想要的功能,但我希望针对单个引用的所有值都将显示在一行上。但是,对于原始表中的每个代码,我都会获得一行代码(请参见下面的结果)。
使用CROSS APPLY似乎是一种方法(在我的代码示例中已注释掉),但是我遇到了一些问题:
希望所有这些都是有道理的。请建议我如何将以下结果折叠为一行。预先感谢。
DECLARE @CODES nvarchar(max)
select @CODES =
stuff(
(
select distinct ',[' + code + ']'
from codetable
for xml path('')
),
1,1,'')
DECLARE @SQL nvarchar(max)
SET @SQL =
N'
SELECT
ref,
' + @CODES + ',
FROM
codetable
--CROSS APPLY
--(
-- VALUES
-- (''code'', convert(varchar(10), code, 120)),
-- (''value'', convert(decimal, value))
--) CA (CODE, VAL)
PIVOT(SUM(value)
FOR code IN (' + @CODES + '))
AS PVTTable2
WHERE
ref = ''101'' AND end_date IS NULL
GROUP BY ref,' + @CODES + '
'
exec sp_executesql @SQL
My original table is like this:
-------------------------
|ref |CODES |VALUE |
-------------------------
|101 |CODE4 |20 |
|101 |CODE1 |2 |
|101 |CODE7 |38 |
The results I get are:
-------------------------------------------------------------------------
|ref |CODE1 |CODE2 |CODE3 |CODE4 |CODE5 |CODE6 |CODE7 |CODE8 |
-------------------------------------------------------------------------
|101 |NULL |NULL |NULL |20 |NULL |NULL |NULL |NULL |
|101 |2 |NULL |NULL |NULL |NULL |NULL |NULL |NULL |
|101 |NULL |NULL |NULL |NULL |NULL |NULL |38 |NULL |
答案 0 :(得分:0)
GROUP BY ref
DECLARE @CODES nvarchar(max)
select @CODES =
stuff(
(
select distinct ',[' + code + ']'
from codetable
for xml path('')
),
1,1,'');
DECLARE @CODESGrp nvarchar(max)
select @CODESGrp =
stuff(
(
select distinct ',min([' + code + '])'
from codetable
for xml path('')
),
1,1,'');
DECLARE @SQL nvarchar(max);
SET @SQL = 'SELECT ref,' + @CODESGrp
+ ' FROM codetable '
+ ' PIVOT(SUM(value) FOR code IN (' + @CODES + ')) AS PVTTable2'
+ ' WHERE ref = 101 GROUP BY ref' ;
exec sp_executesql @SQL;
答案 1 :(得分:0)
数据透视应写为:
DECLARE @cols AS NVARCHAR(MAX),@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(T.CODES)
FROM codetable T
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ref, ' + @cols + ' from
(
SELECT
ref, --< grouping column >,
CODES, --< spreading column >,
VALUE --< aggregation column >
FROM codetable
) PivotData
pivot
(
sum(VALUE)
for CODES in (' + @cols + ')
) p '
exec sp_executesql @query