从表中查询动态数据透视/转换数据的SQL查询

时间:2012-05-14 03:43:42

标签: sql sql-server database sql-server-2008 tsql

我有下表,

Company_ID             part_id     Serial NO
------------------    ----------- --------------
1                     BAU          BAU2512  
1                     BAU          BAU3512
1                     BAU          BAU4512
2                     BAU          BAU5512
2                     BAU          BAU6512
2                     BAU          BAU7512

我想要一个查询来返回

Company_id             Item#1       Item#2         Item#3   
------------------    ---------     -------------  ----------- 
1                     BAU2512       BAU3512        BAU4512
2                     BAU5512       BAU6512        BAU7512

使用SQL Server 2008

赞赏查询的任何帮助

创建样本表。

-- Suppress data loading messages
SET NOCOUNT ON

-- Create Sample Data using a Table Varable
DECLARE @Company TABLE
(Company_ID int,
 part_ID varchar(30),
 SerialNO varchar(30))

-- Load Sample Data
INSERT INTO @Company VALUES (1, 'BAU', 'BAU2512')
INSERT INTO @Company VALUES (1, 'BAU', 'BAU3512')
INSERT INTO @Company VALUES (1, 'BAU', 'BAU4512')
INSERT INTO @Company VALUES (2, 'BAU', 'BAU5512')
INSERT INTO @Company VALUES (2, 'BAU', 'BAU6512')
INSERT INTO @Company VALUES (2, 'BAU', 'BAU7512')

2 个答案:

答案 0 :(得分:2)

啊哈,我认为除了使用动态sql之外别无选择。基于这里的答案PIVOT in sql 2005

下面是我的工作解决方案。

创建表等

-- Create Sample Data using a Table Varable
create table dbo.Company
(Company_ID int,
 part_ID varchar(30),
 SerialNO varchar(30))

-- Load Sample Data
INSERT INTO Company VALUES (1, 'BAU', 'BAU2512')
INSERT INTO Company VALUES (1, 'BAU', 'BAU3512')
INSERT INTO Company VALUES (1, 'BAU', 'BAU4512')
INSERT INTO Company VALUES (2, 'BAU', 'BAU5512')
INSERT INTO Company VALUES (2, 'BAU', 'BAU6512')
INSERT INTO Company VALUES (2, 'BAU', 'BAU7512')

查询

DECLARE @sql AS varchar(max)
DECLARE @pivot_list AS varchar(max) -- Leave NULL for COALESCE technique
DECLARE @select_list AS varchar(max) -- Leave NULL for COALESCE technique

SELECT @pivot_list = COALESCE(@pivot_list + ', ', '') + '[' + CONVERT(varchar, PIVOT_CODE) + ']'
        ,@select_list = COALESCE(@select_list + ', ', '') + '[' + CONVERT(varchar, PIVOT_CODE) + '] AS [col_' + CONVERT(varchar, PIVOT_CODE) + ']'
FROM (
    SELECT DISTINCT PIVOT_CODE
    FROM (
        SELECT Company_ID, SerialNO, ROW_NUMBER() OVER (PARTITION BY Company_ID ORDER BY SerialNO) AS PIVOT_CODE
        FROM Company
    ) AS rows
) AS PIVOT_CODES

SET @sql = '
;WITH p AS (
    SELECT Company_ID, SerialNO, ROW_NUMBER() OVER (PARTITION BY Company_ID ORDER BY SerialNO) AS PIVOT_CODE
    FROM Company
)
SELECT Company_ID, ' + @select_list + '
FROM p
PIVOT (
    MIN(SerialNO)
    FOR PIVOT_CODE IN (
        ' + @pivot_list + '
    )
) AS pvt
'

PRINT @sql

EXEC (@sql)

在这里回答:

http://sqlfiddle.com/#!3/7fd86/1

答案 1 :(得分:1)

看起来你想要一个PIVOT语句。看看here