代码之家  ›  专栏  ›  技术社区  ›  Delta76

如何计算表中每列的值?

  •  1
  • Delta76  · 技术社区  · 16 年前

    UserID     Customer ID status        
    1               1          1
    1               2          1 
    1               3          1
    1               4          2
    1               5          1
    1               6          3
    1               7          2
    2               8          1
    2               9          2 
     ........
    

    我想把这张表总结如下:

     UserID           count(status 1)    count(status 2)   count(status 3)
        1                4                2                     1 
        2                1                2                     3
       .........
    

    4 回复  |  直到 16 年前
        1
  •  10
  •   Guffa    16 年前

    您可以根据UserId分组并汇总不同的状态代码。

    比如:

    select
      UserId,
      sum(case status when 1 then 1 else 0 end) as Status1,
      sum(case status when 2 then 1 else 0 end) as Status2,
      sum(case status when 3 then 1 else 0 end) as Status3
    from SomeTable
    group by UserId
    order by UserId
    

    select UserId, status, count(*)
    from SomeTable
    group by UserId, status
    order by UserId, status
    
        2
  •  1
  •   Kirill Leontev    16 年前
    select userid, 
           count(decode(status, 1, 1, null)),
           count(decode(status, 2, 1, null)),
           count(decode(status, 3, 1, null)),
      from table
     group by userid
    
        3
  •  1
  •   Mark Baker    16 年前
    SELECT *
      FROM ( SELECT UserID,
                    status,
                    COUNT(status)
               FROM <table>
              GROUP BY UserID,
                       status
           )
     PIVOT(COUNT(status) FOR status IN (1,2,3))
    
        4
  •  0
  •   andr    16 年前

    接下来是@Vimvq1987和@Guffa注释:的正确语法 SQL语句 case ... end ,但对于 PL/SQL语言 应该是的 case ... end case

    案例。。。结束 案例。。。结束案例