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

2013-11-09 12:12:08 +08:00
 ithelloworld
现在想要这样的效果:

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语句能不能实现呢?
3248 次点击
所在节点    程序员
5 条回复
msg7086
2013-11-09 12:23:19 +08:00
select a,这里a是什么?

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

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

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

就是这里不太清楚怎么处理。
lichao
2013-11-09 13:08:17 +08:00
用 case 语句,配合 group,简单一句即可搞定,根本不需要什么视图、子查询
ithelloworld
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
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

大概就是这个意思吧

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/88623

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX