• 请不要在回答技术问题时复制粘贴 AI 生成的内容
ithelloworld
V2EX  ›  程序员

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

  •  
  •   ithelloworld · Nov 9, 2013 · 4113 views
    This topic created in 4582 days ago, the information mentioned may be changed or developed.
    现在想要这样的效果:

    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 replies    1970-01-01 08:00:00 +08:00
    msg7086
        1
    msg7086  
       Nov 9, 2013
    select a,这里a是什么?

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

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

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

    就是这里不太清楚怎么处理。
    lichao
        3
    lichao  
       Nov 9, 2013 via iPhone
    用 case 语句,配合 group,简单一句即可搞定,根本不需要什么视图、子查询
    ithelloworld
        4
    ithelloworld  
    OP
       Nov 9, 2013
    @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  
       Nov 9, 2013
    @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

    大概就是这个意思吧
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1009 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 19:05 · PVG 03:05 · LAX 12:05 · JFK 15:05
    ♥ Do have faith in what you're doing.