SQL Server数据透视表查询只返回一行

时间:2016-05-10 12:54:56

标签: sql-server pivot

我的数据是这样的:

ID  ColumnName  columnnvalue
----------------------------- 
13  seraialnew   tester name
13  serial        123123
13  seraialnew    am444
13  serial        33333


SELECT  id,seraialnew,serial
  FROM (
   SELECT id,columnnvalue, ColumnName  FROM dbo.formValues
  ) cols
PIVOT(
    MAX(id)
    FOR ColumnName IN(seraialnew,serial)
)p

并获得单行结果而不是多次

1 个答案:

答案 0 :(得分:1)

如果你有相同的id,那么只有一个字符串,所以我改变了你的2行的id:

;WITH formValues AS (
SELECT *
FROM (VALUES
(13,'seraialnew','tester name'),
(13,'serial','123123'),
(14,'seraialnew','am444'),
(14,'serial','33333')
) as t(ID, ColumnName, columnnvalue)
)

SELECT  id,seraialnew,serial
  FROM (
   SELECT id,columnnvalue, ColumnName
   FROM formValues
  ) cols
PIVOT(
    MAX(columnnvalue)
    FOR ColumnName IN(seraialnew,serial)
)p

会给你:

id  seraialnew  serial
13  tester name 123123
14  am444       33333

另一种方式:

SELECT *
FROM (
    SELECT  id,
            columnnvalue,
            ColumnName+CAST(ROW_NUMBER() OVER (PARTITION BY ColumnName ORDER BY ColumnName) as nvarchar(1)) as ColumnName
    FROM formValues
) cols
PIVOT(
    MAX(columnnvalue)
    FOR ColumnName IN(seraialnew1,serial1,seraialnew2,serial2)
)p

使用相同的id = 13会给你:

id  seraialnew1 serial1 seraialnew2 serial2
13  am444       33333   tester name 123123