将列值转换为字段并在sql server中保留其他值

时间:2015-10-27 08:56:36

标签: sql-server

有人可以帮助我将下面提到的原始表格转换为所需的表格吗?我想我以前做过,只是我现在无法做到。谢谢您的帮助。

Original Table              
year    school  program count   
2014     A      XYZ     3   
2014     A      DEF     1   
2014     B      XYZ     2   
2014     B      DEF     4   
2014     B      GHI     5   
2014     C      XYZ     3   

Table Required              
YEAR    SCHOOL  XYZ DEF GHI
2014     A      3   1   0
2014     B      2   4   5
2014     C      3   0   0

3 个答案:

答案 0 :(得分:1)

您可以尝试使用此查询。它首先计算一个临时表,其中包含每条记录的XYZDEFGHI计数。然后外部查询汇总每个年/学校组合的这些计数。

SELECT t.year, t.school,
    SUM(t.XYZ) AS XYZ, SUM(t.DEF) AS DEF, SUM(t.GHI) AS GHI
FROM
(
    SELECT year, school,
        CASE WHEN program = 'XYZ' THEN count ELSE 0 END AS XYZ
        CASE WHEN program = 'DEF' THEN count ELSE 0 END AS DEF
        CASE WHEN program = 'GHI' THEN count ELSE 0 END AS GHI
    FROM table
) t
GROUP BY t.year, t.school

答案 1 :(得分:1)

尝试使用Dynamic Pivot,

CREATE TABLE #Your_Table
(
    YEAR INT,
    SCHOOL CHAR(1),
    PROGRAM VARCHAR(10),
    COUNT INT
)

INSERT INTO #Your_Table
VALUES      (2014,'A','XYZ',3),
            (2014,'A','DEF',1),
            (2014,'B','XYZ',2),
            (2014,'B','DEF',4),
            (2014,'B','GHI',5),
            (2014,'C','XYZ',3) 

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
DECLARE @TempColumnname AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column 
SELECT @ColumnName = ISNULL(@ColumnName + ',', '')
                     + Quotename(PROGRAM)
FROM   (SELECT DISTINCT PROGRAM
        FROM   #Your_Table) AS Courses

SELECT @TempColumnname = ISNULL(@TempColumnname + ',', '')
                         + 'ISNULL(' + Quotename(PROGRAM) + ',0) AS '+Quotename(PROGRAM)
FROM   (SELECT DISTINCT PROGRAM
        FROM   #Your_Table) AS Courses
--PRINT @TempColumnname

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = N'SELECT Year, School, ' + @TempColumnname
                         + 'FROM #Your_Table PIVOT(SUM(Count) 
          FOR PROGRAM IN (' + @ColumnName + ')) AS PVTTable'

--Execute the Dynamic Pivot Query
EXEC SP_EXECUTESQL
  @DynamicPivotQuery 

答案 2 :(得分:0)

使用PIVOT

SELECT
  YEAR, 
  SCHOOL, 
  COALESCE([XYZ], 0) [XYZ], 
  COALESCE([DEF], 0) [DEF], 
  COALESCE([GHI], 0) [GHI]
INTO
  Table_Required
FROM
  Original_table
PIVOT
  (SUM([count])  
FOR program
  in([XYZ],[DEF],[GHI])  
  )AS p
ORDER BY YEAR, SCHOOL