【问题标题】:How to group rows into two groups in sql?如何在sql中将行分成两组?
【发布时间】:2012-10-29 16:56:00
【问题描述】:

假设我有这样一张桌子:

id|time|operation
1  2      read
2  5      write
3  3      read
4  7      read
5  2      save
6  1      open

现在我想做两件事:

  1. 将所有这些记录分为两组: 1) 操作等于“读取”的所有行 2) 所有其他行。
  2. 总结每组的时间。

这样我的查询只会产生两行。

到目前为止我得到的是:

select 
 sum(time) as total_time,
 operation
group by
 operation
;

虽然这给了我很多组,具体取决于不同操作的数量。

我怎样才能把它们分成两类?

干杯!

【问题讨论】:

    标签: sql group-by


    【解决方案1】:

    group by 可以带任意子句,所以

    GROUP BY (operation = 'read')
    

    会起作用。本质上,您将根据比较的布尔结果进行分组,而不是操作字段的值,因此“读取”的任何记录都将分组1,任何未读取的记录将分组0

    【讨论】:

    • group by case when operation='real' then 1 else 0 end 可以解决这个问题,但是你不得不在所有东西上使用聚合
    • 非常感谢!这很好用。我只想改进一件事。是否可以更改与“读取”不同的组中的操作值?所以我会得到例如:[newline] total_time operation [newline] 267 others [newline] 120 read [newline]
    • group by (operation = 'read'), operation。这会将读取分成他们自己的组,并且仍然将其他所有内容分组到他们自己的个人组中。
    【解决方案2】:

    或者,您也可以使用case 语句:

    select
    case when operation != 'read' then 'other'
      else operation end as operation
    ,sum(time) as total_time
    from table
    group by case when operation != 'read' then 'other'
      else operation end;
    

    【讨论】:

      【解决方案3】:

      试试

      SELECT T.op, sum(T.time)
      FROM ( SELECT time, CASE operation 
                      WHEN 'read' THEN 'read' ELSE 'not read' END AS op ) T
      GROUP BY T.op
      

      【讨论】:

        猜你喜欢
        • 2012-05-19
        • 1970-01-01
        • 1970-01-01
        • 2021-08-20
        • 2019-01-28
        • 2014-10-21
        • 1970-01-01
        • 2016-04-22
        • 2020-10-15
        相关资源
        最近更新 更多