【问题标题】:mysql group by having minmysql 组由 min
【发布时间】:2013-04-12 02:09:05
【问题描述】:

下面是表格数据(一小块),基本上我希望只查询按帐户编号分组时具有最小 original_date_ctr 的行。

我尝试过使用 HAVING(MIN()) 和 where = Min() 以及其他没有运气的方法。

这里的正确结果会给我 id_ctr 688、1204 和 1209

id_ctr  account_number_cus  original_date_ctr   mrc_ctr  
------  ------------------  -----------------  ----------
   688               20062  2008-05-17             138.97
  1204              151604  2006-08-10           42000.00
  1209              151609  2006-06-29             968.68
  1367               20062  2011-10-27             207.88
  1434              151609  2009-09-10            1469.62
  1524              151604  2009-09-01           36999.99
  1585              151609  2012-05-31            1683.88

【问题讨论】:

    标签: mysql having


    【解决方案1】:

    使用连接执行此操作会更快:

    SELECT a.*
    FROM mytable a
    LEFT JOIN mytable b
      ON a.account_number_cus = b.account_number_cus
      AND b.original_date_ctr < a.original_date_ctr
    WHERE b.id_ctr IS NULL
    

    【讨论】:

    • 这应该是公认的答案,MySQL 中的派生表是性能杀手。
    【解决方案2】:

    您可以通过以下方式执行此操作:

    select t1.id_ctr,
        t1.account_number_cus,
        t1.original_date_ctr,
        t1.mrc_ctr  
    from yourtable t1
    inner join
    (
        select min(original_date_ctr) as mindate, account_number_cus
        from yourtable
        group by account_number_cus
    ) t2
        on t1.account_number_cus = t2.account_number_cus
        and t1.original_date_ctr = t2.mindate
    

    SQL Fiddle with Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-18
      • 1970-01-01
      • 2011-08-07
      • 2014-02-17
      • 1970-01-01
      • 2012-07-25
      • 2012-10-28
      相关资源
      最近更新 更多