【问题标题】:Count the total records containing specific values计算包含特定值的总记录
【发布时间】:2012-04-17 09:35:30
【问题描述】:

我有一个问题,希望你们能帮助我。

我有一个包含两列的表格:

type           // contains 2 different values: "Raid" and "Hold"
authorization  // contains 2 different values: "Accepted" or "Denied"

我需要创建一个返回如下值的视图:

TYPE:RAID     ACCEPTED:5          DENIED:7

基本上我想知道TYPE 中有多少值是“Raid”,然后有多少 它们是“接受”和“拒绝”。

提前谢谢你!!

【问题讨论】:

    标签: sql count case conditional-statements


    【解决方案1】:
    SELECT
       Type
      ,sum(case Authorization when 'Accepted' then 1 else 0 end) Accepted
      ,sum(case Authorization when 'Denied' then 1 else 0 end) Denied
     from MyTable
     where Type = 'RAID'
     group by Type
    

    【讨论】:

      【解决方案2】:

      您可以将COUNTCASE 语句结合使用

      SELECT COUNT(CASE authorization WHEN 'denied' THEN 1 ELSE NULL END) as denied,
        COUNT(CASE authorization WHEN 'authorized' THEN 1 ELSE NULL END) as authorized
      FROM table
      WHERE type = 'RAID'
      

      SUM(CASE …) 也是可能的,但您必须在 ELSE 子句中返回 0 而不是 NULL

      【讨论】:

      • 这不会像这样工作。 CASE WHEN 需要一个 END 来完成块。
      • @Magisch:是的,你是对的。感谢您指出,我已经修复了 sn-p!
      【解决方案3】:

      这段代码应该适用于 mySQL

      SELECT type, COUNT(*)
      FROM table
      GROUP BY type;
      

      SELECT type, authorization, COUNT(*)
      FROM table
      GROUP BY type, authorization;
      

      【讨论】:

        【解决方案4】:
        select count(*) as count from tbl_name where type='Raid'
        

        type=raid 的总数

        你是在说这种话吗?

        【讨论】:

          【解决方案5】:

          嘿,这可能会有所帮助:-

          select type as 'TYPE',sum(Denied) as 'DENIED',sum(Accepted) as 'AUTHORIZED' from
          (
           SELECT type,0 as 'Denied',count(*) as 'Accepted' from t where authorization = 'Accepted'    group by type
           union all
           SELECT type,count(*) as 'Denied',0 as 'Accepted' from t where authorization = 'Denied'     group by type ) as sub_tab group by TYPE;
          

          【讨论】:

          • 干草是给马用的。
          猜你喜欢
          • 1970-01-01
          • 2021-10-03
          • 1970-01-01
          • 1970-01-01
          • 2013-03-19
          • 2019-08-29
          • 1970-01-01
          • 2018-06-13
          • 2022-01-13
          相关资源
          最近更新 更多