【问题标题】:counting with conditions in mysql用mysql中的条件计数
【发布时间】:2011-09-27 15:45:21
【问题描述】:

我有点卡在一个非常简单的查询中

我在表格中有这 4 列

id1(唯一),id2(可以重复),更新(布尔),updated_on

我现在想要的是在表单中得到一个摘要

id2,更新次数,最大值(updated_on)

简而言之,我希望结果按最近的 updated_on 排序,同时计算此 id2 where update=1 的所有行

对于没有任何 update=1 的 id,显示 0,最大 update_on

______________________ id2|_count__|___日期__ 1 | 0 | 2005 年 11 月 3 日, 3 | 5 | 2004 年 11 月 3 日, 6 | 3 | 2003 年 11 月 3 日, 2 | 0 | 2002 年 11 月 3 日,

我使用了这个查询:

从表中选择 id2, count(updated),max(updated_on) 其中更新=1 按需要id_to分组

但是这个查询不会带来 count 为 0 的结果(原因很明显,因为我在 where 子句中添加了一个条件)

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    布尔字段为 1 表示 true,0 表示 false
    您可以使用它来获取所有updated = true 行的计数。

    SELECT
      id2
      , SUM(updated) as updates
      ,MAX(updated_on) as last_update
    FROM table1
    GROUP BY id2
    ORDER BY last_update DESC
    

    【讨论】:

      【解决方案2】:
      select id2, 
             count(case 
                     when updated=1 then updated 
                     else null 
                   end) updates_count,
             max(updated_on) last_updated
      from table
      group by id2
      order by last_updated desc
      

      【讨论】:

        【解决方案3】:
        select id2, 
               SUM(CASE WHEN updated=1 THEN 1 ELSE 0 END) AS UpdatedCount,
               max(updated_on) 
            from table
            group by id2
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-09-23
          • 2018-02-23
          • 1970-01-01
          • 2022-06-15
          • 2012-04-05
          • 1970-01-01
          • 2015-08-19
          相关资源
          最近更新 更多