【问题标题】:How to count table rows for each value in SQL?如何计算 SQL 中每个值的表行数?
【发布时间】:2018-12-30 12:56:58
【问题描述】:

我是新来的,所以如果它没有固定的主题,请修复我。 我有这张桌子:

id | uid | month | year
-----------------------
1 | 5 | 12 | 2018
2 | 5 | 12 | 2018
3 | 9 | 12 | 2018
4 | 3 | 01 | 2019

我想计算每个 uidmonthyear 值等于 - month=12 AND year=2018 的次数

例如,我想得到这样的响应:

uid=5 - count = 2
uid=9 - count = 1

这怎么可能?

【问题讨论】:

标签: php mysql sql


【解决方案1】:

group by uid:

select uid, count(*) as counter
from table
where month = 12 and year = 2018
group by uid 

【讨论】:

  • 您好,首先感谢您的回答。我尝试按计数对结果进行排序,这是我添加到查询中的内容:ORDER BY count(*) DESC 有什么问题?
  • 哦,对不起,我的错 - 它工作正常,没有订单。感谢您的最佳回答!
  • order by 没问题,有什么问题?
  • 查看我的最后评论
  • 好吧,你发帖时我正在打字。
【解决方案2】:

您可以使用条件聚合:

select uid,
       sum(case when year = 2018 and month = 12 then 1 else 0 end) as cnt
from t
group by uid;

这将包括计数为 0 的 uids。如果您只想要计数大于 0 的 uid,请使用 where 子句:

select uid, count(*)
from t
where year = 2018 and month = 12
group by uid;

【讨论】:

    【解决方案3】:

    从表中选择uid,count(*),其中year=2018 and month=12 group by uid

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-08
      • 1970-01-01
      • 1970-01-01
      • 2020-06-05
      • 1970-01-01
      • 2020-04-05
      相关资源
      最近更新 更多