我有第一个这样的表,它包含平台及其平台代码
+-----------+------+
| platforms | code |
+-----------+------+
| java | 1 |
| .net | 2 |
| perl | 3 |
+-----------+------+
我的第二张表包含如下所示的列。
+-------+------+------+------+
| pname | code | year | deve |
+-------+------+------+------+
| a | 1 | 2018 | abia |
| b | 1 | 2017 | arun |
| c | 2 | 2018 | abia |
| d | 3 | 2017 | arun |
| e | 2 | 2017 | arun |
| f | 3 | 2018 | abia |
+-------+------+------+------+
预期的数据透视格式的结果如下:
+-----+-------+------+------+------+
| year| deve | .net | java | perl |
+-----+-------+------+------+------+
| 2018| abia | 1 | 1 | 1 |
| 2017| arun | 1 | 1 | 1 |
+-----+-------+------+------+------+
答案 0 :(得分:2)
尝试使用符合您期望的Pivot脚本
DECLARE @Table AS TABLE
(platforms VARCHAR(20), code INT)
INSERT INTO @Table
SELECT 'java', 1 UNION ALL
SELECT '.net', 2 UNION ALL
SELECT 'perl', 3
DECLARE @Table2 AS TABLE
(pname VARCHAR(20), code INT,[year] INT, deve VARCHAR(20))
INSERT INTO @Table2
SELECT 'a',1,2018,'abia' UNION ALL
SELECT 'b',1,2017,'arun' UNION ALL
SELECT 'c',2,2018,'abia' UNION ALL
SELECT 'd',3,2017,'arun' UNION ALL
SELECT 'e',2,2017,'arun' UNION ALL
SELECT 'f',3,2018,'abia'
SELECT [year],deve,MAX([java]) AS [java],MAX([.net]) AS [.net],MAX([perl] ) AS [perl]
FROM
(
SELECT platforms,CASE WHEN pname IS NOT NULL THEN 1 ELSE NUll END AS pname ,A.code ,deve,[year] FROM @Table2 A
INNER JOIN @Table B
ON A.code=b.code
)
AS SRC
PIVOT
(
MAX(pname) FOR platforms IN( [java],[.net],[perl] )
) AS PVT
GROUP BY [year],deve
结果
year deve java .net perl
------------------------------------
2018 abia 1 1 1
2017 arun 1 1 1
答案 1 :(得分:1)
在需要动态添加列以获取特定结果时适合使用动态sql方法进行数据透视
CREATE TABLE #Table
(platforms VARCHAR(20), code INT)
INSERT INTO #Table
SELECT 'java', 1 UNION ALL
SELECT '.net', 2 UNION ALL
SELECT 'perl', 3
CREATE TABLE #Table2
(pname VARCHAR(20), code INT,[year] INT, deve VARCHAR(20))
INSERT INTO #Table2
SELECT 'a',1,2018,'abia' UNION ALL
SELECT 'b',1,2017,'arun' UNION ALL
SELECT 'c',2,2018,'abia' UNION ALL
SELECT 'd',3,2017,'arun' UNION ALL
SELECT 'e',2,2017,'arun' UNION ALL
SELECT 'f',3,2018,'abia'
DECLARE @Columns nvarchar(max),
@IsnullColumns nvarchar(max),
@Sql nvarchar(max)
SELECT @Columns= STUFF((SELECT ', '+QUOTENAME(platforms) FROM #Table FOR XML PATH ('')),1,1,'')
SELECT @IsnullColumns=STUFF((SELECT ', '+'MAX('+QUOTENAME(platforms)+') AS ' +QUOTENAME(platforms) FROM #Table FOR XML PATH ('')),1,1,'')
SET @Sql='
SELECT[year],deve, '+@IsnullColumns+'
FROM
( SELECT platforms,
CASE WHEN pname IS NOT NULL THEN 1 ELSE NUll END AS pname ,A.code ,deve,[year]
FROM #Table2 A
INNER JOIN #Table B
ON A.code=b.code
) AS SRC
PIVOT
(MAX(pname) FOR platforms IN('+@Columns+')
) AS PVT
GROUP BY [year],deve'
PRINT @Sql
EXEC (@Sql)
结果
year deve java .net perl
------------------------------------
2018 abia 1 1 1
2017 arun 1 1 1