SQL,使用math将行转换为列

时间:2015-03-27 11:24:57

标签: mysql sql sql-server tsql

我有这张桌子:

Player    Routes   Colors

 GIN         2      RED    
 GIN         1      BLU    
 GIN         5      BLAS    
 GIN         1      TREN    
 GIN         2      RED    
 PON         1      TREN
 PON         4      BLU
来自带有union all的查询的

,如下所示:

select *
from (
        select  DISTINCT Colors.Name [Colors]
              , COUNT(routes.idRoutes) [Routes]
              , Routes.cdRoutes [Doc]
        from Routes
        inner join Colors on Colors.Name blablabla
        where blablabla
        group by Colors.Name, Routes.cdRoutes

    ) dates

我需要有一个这样的表:

Colors    GIN    PON

 RED       4      0 
 BLU       1      4
 BLAS      5      0
 TREN      1      1

怎么样?我想我可以在不使用PIVOT功能的情况下获得它,对吗?

1 个答案:

答案 0 :(得分:1)

你可以这样做(即使不使用PIVOT):

select
    Colors,
    sum(case when Player = 'GIN' then Routes else 0 end) as GIN,
    sum(case when Player = 'PON' then Routes else 0 end) as PON
from your_query_or_Table
group by Colors