如何使用自定义方式将一个数据表复制到另一个数据表

时间:2015-06-29 05:24:27

标签: c# sql-server

Series_name Age value
------------------------
Per_03  5.00    13.7000
Per_03  5.50    13.6000
Per_03  6.00    13.6000
Per_03  6.50    13.6000
Per_03  7.00    13.6000
Per_03  7.50    13.7000
Per_03  8       13.8000
Per_10  5.00    14.2000
Per_10  5.50    14.1000
Per_10  6.00    14.0000
Per_10  6.50    13.9000
Per_10  7.00    14.0000
Per_10  7.50    14.1000
Per_10  8.00    14.2000
Per_25  5.00    14.5000
Per_25  5.50    14.6000
Per_25  6.00    14.5000
Per_25  6.50    14.6000

我有这样的数据表,我必须将每个不同的系列名称作为datacolunm并将它们各自的值放入它们的年龄,系列名称列的行和预期的结果是这里的系列名称必须动态地采取多少不同的列中的系列名称每个系列名称将成为列名称,系列名称不是硬编码的.....

age     Per_03  Per_10  Per_25
-------------------------------
5.00    13.7000 14.2000 14.5000
5.50    13.6000 14.1000 14.6000
6.00    13.6000 14.0000 14.5000
6.50    13.6000 13.9000 14.6000
7.00    13.6000 14.0000 14.6000
7.50    13.7000 14.1000 14.7000
8.00    13.7000 14.2000 14.8000

2 个答案:

答案 0 :(得分:1)

使用条件聚合:

SQL Fiddle

SELECT
    age,
    Per_03 = MAX(CASE WHEN Series_Name = 'Per_03' THEN vaue END),
    Per_10 = MAX(CASE WHEN Series_Name = 'Per_10' THEN vaue END),
    Per_25 = MAX(CASE WHEN Series_Name = 'Per_25' THEN vaue END)
FROM tbl
GROUP BY age
ORDER BY age

如果Series_Name未知,您可以使用动态交叉表:

SQL Fiddle

DECLARE @sql1 VARCHAR(4000) = ''
DECLARE @sql2 VARCHAR(4000) = ''
DECLARE @sql3 VARCHAR(4000) = ''

SELECT @sql1 =
'SELECT
    age
'

SELECT @sql2 = @sql2 +
'   , MAX(CASE WHEN Series_Name = ''' +  Series_Name + ''' THEN value END) AS [' + Series_Name + ']' + CHAR(10)
FROM(
    SELECT DISTINCT Series_Name FROM tbl
)t
ORDER BY Series_Name
SELECT @sql3 = 
'FROM tbl
GROUP BY age
ORDER BY age'

PRINT (@sql1 + @sql2 + @sql3)
EXEC (@sql1 + @sql2 + @sql3)

答案 1 :(得分:1)

或者,如果您有SQL SERVER 2005或更高版本,那么您可以使用动态PIVOT,如下所示:

DECLARE @ColumnList VARCHAR (MAX)
DECLARE @SQL VARCHAR(MAX)

-- Create a list of distinct Series_names which will become column headers
SELECT @ColumnList = COALESCE(@ColumnList + '], [','[') + CAST(T.Series_name AS VARCHAR(12)) FROM (SELECT DISTINCT Series_name FROM YourTable) T
SET @ColumnList = @ColumnList + ']'

SET @SQL = '
SELECT
  [Age], ' + @ColumnList + '
FROM
(  
  SELECT
    A.Age,
    A.Series_Name,
    A.Value
  FROM
      YourTable A
)  T
PIVOT
(
    SUM(Value)
    FOR T.Series_Name IN (' + @ColumnList + ')
) AS PVT'

EXEC (@SQL)