V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
ithelloworld
V2EX  ›  程序员

这样的需求能不能用一条SQL实现?

  •  
  •   ithelloworld · 2013-11-09 12:12:08 +08:00 · 3242 次点击
    这是一个创建于 3820 天前的主题,其中的信息可能已经有所发展或是发生改变。
    现在想要这样的效果:

    name monthly_count total_count
    a 10 20
    b 15 25

    a 的 monthly_count 取得方法为:

    select a, count(*) as monthly_count from table_name where updated_at = yyyymm

    total_count 的取得条件是:

    select count(*) as total_count from table_name

    即不加按月统计。

    用一条SQL语句能不能实现呢?
    5 条回复    1970-01-01 08:00:00 +08:00
    msg7086
        1
    msg7086  
       2013-11-09 12:23:19 +08:00
    select a,这里a是什么?

    聚合的话要用group by。你这是一个筛选聚合加一个全表聚合么?分开写比较好些吧。

    一定要绑一起的话考虑开视图再join,或者做子查询。
    ithelloworld
        2
    ithelloworld  
    OP
       2013-11-09 12:27:04 +08:00
    @msg7086 a 应该是“name”,不好意思,写错了:)

    > 开视图再join,或者做子查询

    就是这里不太清楚怎么处理。
    lichao
        3
    lichao  
       2013-11-09 13:08:17 +08:00 via iPhone
    用 case 语句,配合 group,简单一句即可搞定,根本不需要什么视图、子查询
    ithelloworld
        4
    ithelloworld  
    OP
       2013-11-09 13:58:33 +08:00
    @lichao 我得到这样一种方法:

    SELECT t.name
    , SUM(IF(t.updated_at = yyyymm)) AS monthly_count
    , SUM(1) AS total_count
    FROM table_name t
    GROUP
    BY t.name

    你的方式能分享一下吗?
    lichao
        5
    lichao  
       2013-11-09 20:17:59 +08:00
    @ithelloworld

    select t.name,
    sum(case when t.updated_at = yyyymm then 1 else 0 end) as monthly_count,
    sum(1) as total_count
    from table_name t
    group by t.name

    大概就是这个意思吧
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5413 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 03:38 · PVG 11:38 · LAX 20:38 · JFK 23:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.