根据行值(pivot?)创建一个字段

时间:2014-12-04 21:52:18

标签: sql sql-server

我有一个返回多行结果的查询。我的查询如下:

select * from containertbl where bol_key = 236377502

我的结果如下:

query results

我希望结果看起来像这样

desired results

我已经尝试了数据透视表(并尝试了几次,但从未获得任何结果),但我不希望该值成为字段名称。此外,容器的数量是未知的。

提前感谢您的任何帮助!

1 个答案:

答案 0 :(得分:0)

我认为在这种情况下,动态sql是唯一的方法,因为旋转列的确切数量是未知的。你也可以看看here

DECLARE @query AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

-- A nested query is used here to generate the required sequence for the column names of the
-- pivoted columns, i.e. [container1],[container2],[container3],[container4],[container5],[container6] etc. 
SELECT @ColumnName= ISNULL(@ColumnName + ',','') + QUOTENAME(PivotColumnName)
FROM (SELECT bol_key, containerId, 'container' + CONVERT(VARCHAR(10), rn) AS PivotColumnName
FROM (
   SELECT bol_key, containerId, ROW_NUMBER() OVER (PARTITION BY bol_key ORDER BY containerId) AS rn 
   FROM containertbl
) t ) s

--Prepare the PIVOT query using the columns names calculated
SET @query = 
  N'SELECT bol_key, ' + @ColumnName + '
    FROM (SELECT bol_key, containerId,' + CHAR(39) + 'container' + CHAR(39) + ' + CONVERT(VARCHAR(10), rn) AS PivotColumnName
          FROM (
            SELECT bol_key, containerId, ROW_NUMBER() OVER (PARTITION BY bol_key ORDER BY containerId) AS rn 
            FROM containertbl) t ) s    
    PIVOT(MAX(containerId) 
          FOR PivotColumnName IN (' + @ColumnName + ')) AS PvtTable'

--Execute the dynamic pivot query
EXEC sp_executesql @query

SQL Fiddle here