【问题标题】:Counting number of months; is the number of months with more than 2000 transactions greater than 3计算月数;是大于 3 的超过 2000 笔交易的月数
【发布时间】:2020-01-10 22:01:48
【问题描述】:

我想计算超过 2000 笔交易的月数。 我现在已经计算了每个月的交易次数,但是我怎样才能添加额外的条件呢? 这是我现在的查询:

select 
run_date, count(1) as Number_Of_Transactions
from 
transactions
where
run_date = '08-10-19' 
or
run_date = '08-9-19' 
or 
run_date = '08-8-19' 
or
run_date = '08-7-19'   
or
run_date = '08-6-19'   
or
run_date = '08-5-19'
group by 
run_date

这是结果:

【问题讨论】:

  • 用您正在使用的数据库标记您的问题。
  • 您确定这是您统计的每月交易吗?
  • 请注意,WHERE foo = 'a' OR foo = 'b' OR foo = 'c' 之类的内容可以简化为 WHERE foo IN ('a', 'b', 'c')
  • 我使用的数据库是Oracle
  • @GordonLinoff 我尝试了以下操作: select count() from (select year(run_date) as yyyy, month(run_date) as mm, count() as num_transactions from transactions按年份(run_date)、月份(run_date)分组,count(*)>1)ym;但我收到以下错误消息: ORA-00904: "MONTH": ongeldige ID 00904. 00000 - "%s: invalid identifier" *原因:*操作:错误在行:118 列:32 你有任何提示如何解决这个问题?

标签: sql


【解决方案1】:

您将使用两个级别的聚合。众所周知,日期函数依赖于数据库,但类似这样:

select count(*)
from (select year(run_date) as yyyy, month(run_date) as mm,
             count(*) as num_transactions
      from transactions
      group by year(run_date), month(run_date)
      having count(*) > 2000
     ) ym

【讨论】:

  • 我很惊讶YEAR()MONTH() 可以应用于in SQL Server 等字符串,例如08-10-19
  • MySQL 这提供了错误的结果,但是
  • @Cid 我相信是从字符串到日期的转换,然后完成了年份或月份的功能......不能对不满足所有日期格式条件的字符串进行转换。
猜你喜欢
  • 2015-06-24
  • 1970-01-01
  • 2022-08-18
  • 2013-09-16
  • 1970-01-01
  • 2019-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多