将SQL表行放入列

时间:2015-08-06 14:29:52

标签: sql-server pivot

我正在尝试创建一个将返回一组带有值的列的查询,这是我目前所获得的,

╔═══╦═══════════════╦═════════════╗
║   ║ProgramTypeName║  TypeAmount ║
╠═══╬═══════════════╬═════════════╣
║ 1 ║ Center        ║      4      ║
║ 2 ║ School        ║      2      ║
╚═══╩═══════════════╩═════════════╝

我从表中获取ProgramTypeName,而TypeAmount,Count(ProgramTypeName)。

我试图达到这一点,

╔═══╦═══════════════╦═════════════╗
║   ║Center         ║  School     ║
╠═══╬═══════════════╬═════════════╣
║ 1 ║       4       ║      2      ║
╚═══╩═══════════════╩═════════════╝

关于我能做些什么来实现这个目标?

@Indian这是我从你的建议中得到的结果,

╔═══╦═══════════════╦═════════════╗
║   ║Center         ║  School     ║
╠═══╬═══════════════╬═════════════╣
║ 1 ║       NULL    ║    NULL     ║
║ 2 ║       NULL    ║    NULL     ║
║ 3 ║       NULL    ║    2        ║
╚═══╩═══════════════╩═════════════╝

正常查询数据时,我有这个,

╔═══╦══════════╦═════════════╦════════╦════════════════╦═══════╗
║   ║License   ║  ProgName   ║ Id     ║ProgramTypeName ║Amount ║
╠═══╬══════════╬═════════════╬════════╬════════════════╬═══════╣
║ 1 ║ 45871    ║ TestName    ║  1     ║ Center         ║ 4     ║
║ 2 ║ 45871    ║ TestName    ║  1     ║ School         ║ 4     ║
║ 3 ║ 45871    ║ TestName    ║  1     ║ Other          ║ 2     ║
╚═══╩══════════╩═════════════╩════════╩════════════════╩═══════╝

3 个答案:

答案 0 :(得分:2)

使用conditional Aggregate将同时适用于MysqlSql Server

select 
max(case when ProgramTypeName = 'Center' then TypeAmount END) as Center
max(case when ProgramTypeName = 'School' then TypeAmount END) as School
From (select ProgramTypeName ,Count(ProgramTypeName) from x ...) A
Group by somecol

答案 1 :(得分:1)

我能够使用它,

Select Max(Case When A.ProgName = 'Center'  Then TypeAmount End) As Center,
       Max(Case When A.ProgName = 'School'  Then TypeAmount End) As School,
       Max(Case When A.ProgName = 'Other'   Then TypeAmount End) As Other
From T_Prog P Inner Join (Select ProgID,
                                 ProgName, 
                                 Count(ProgName) As ProgAmount 
                          From T_ProgType_Join PTJ Inner Join T_ProgramType PTJ On PT.ProgramTypeId = PT.ProgramTypeId 
                          Where PTJ.ProgramId = @ProgID
                          Group by ProgName, ProgID) A On A.ProgID= P.ProgID
Where PTJ.ProgID= @ProgID

答案 2 :(得分:0)

测试数据

DECLARE @Table TABLE (ProgrameTypeName VARCHAR(20))
INSERT INTO @Table VALUES 
 ('Central'),('Central'),('Central'),('Central')
,('School'),('School')

查询

SELECT *
FROM @Table t
        PIVOT (
               COUNT(ProgrameTypeName)
               FOR ProgrameTypeName
               IN ([Central],[School])
              )p

结果

╔═════════╦════════╗
║ Central ║ School ║
╠═════════╬════════╣
║    4    ║   2    ║
╚═════════╩════════╝