【问题标题】:SQL, Transform rows to columns with mathSQL,使用数学将行转换为列
【发布时间】:2015-03-27 11:24:57
【问题描述】:

我有这张桌子:

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 函数来获取它,对吧?

【问题讨论】:

    标签: mysql sql sql-server tsql


    【解决方案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
    

    【讨论】:

    • 亲爱的安迪,你的脚本很漂亮,除了我需要“Routes.idRoutes”的计数。如何?我收到此错误:无法对包含聚合或子查询的表达式执行聚合函数。
    • @JohnSam 等等......您在查询中选择了COUNT(routes.idRoutes) 作为Routes。假设我的查询正在使用您原始查询的结果 - 所以它只是对 Routes 求和,这是根据您的查询定义的 isRoutes 计数。您应该将 your_query_or_Table 从我的查询更改为您的查询文本本身
    猜你喜欢
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    • 2011-10-04
    • 1970-01-01
    相关资源
    最近更新 更多