【问题标题】:Query to Display data if the value is greater than 3 in any of the last 3 months in SQL Server如果 SQL Server 中最近 3 个月的任何一个值大于 3,则查询以显示数据
【发布时间】:2020-09-09 12:41:22
【问题描述】:

如果过去 3 个月中的任何一个月的值>=3,我想过滤该值。查看我在输出中需要突出显示的图像。

我尝试过的查询。

select Application_Infrastructure,year,month_name,count(ticket_no) as 'CN' from [service_delivery]
where month_num in (MONTH(getdate()),MONTH(getdate())-1,MONTH(getdate())-2,MONTH(getdate())-3)
group by Application_Infrastructure,year,month_name 
having count(ticket_no)>=3
 order by Application_Infrastructure,CN 

having count(ticket_no)>=3 正在消除该月小于 3 的值。

Please see the image

【问题讨论】:

  • 请向我们展示生成当前结果的查询。
  • 你试过什么?为什么它不起作用?在您忘记包含在问题中的查询之前,您的数据是什么样的(也不要使用数据图像,将其提供为表格格式的text 或 DDL 和 DML 语句)。此外,现在完全不支持 SQL Server 2008;我强烈建议您在(非常)不久的将来优先升级。
  • 我以该数据为例,查询是 select Application_Infrastructure,year,month_name,count(ticket_no) as 'CN' from [service_delivery] where month_num in (MONTH(getdate()),MONTH( getdate())-1,MONTH(getdate())-2,MONTH(getdate())-3) 按 Application_Infrastructure,year,month_name 分组,count(ticket_no)>=3 order by Application_Infrastructure,CN 这消除了不大于 3 ,但对我来说,如果任何月份值大于 3,则必须显示整个 Application_Infrastructure 数据。
  • edit 你的问题@MUHAMMEDTHAYYABSAWOODSYED。 cmets 是针对 cme​​ts 的,而不是针对您的问题中应该包含的信息。
  • 谢谢拉努,我已经编辑了这个问题。

标签: sql sql-server tsql sql-server-2008 group-by


【解决方案1】:

您可以使用窗口 max() 在子查询中计算 3 个月内每个 application_infrastructure 的最大计数,并在外部查询中按该值进行过滤。

select *
from (
    select 
        application_infrastructure, 
        year,
        month_name,
        count(ticket_no) cn,
        max(count(ticket_no)) over(partition by application_infrastructure) max_cn
    from service_delivery
    where datefromparts(year, month_num, 1) 
        >= dateadd(month, -3, datefromparts(year(getdate()), month(getdate()), 1))
    group by application_infrastructure, year, month_num, month_name
) t
where max_cn <= 3
order by application_infrastructure, cn

请注意,我重写了您的 where 子句,以便它在过去 3 个月内正确且更有效地过滤。

【讨论】:

  • 现在我收到“datefromparts”错误,它不是可识别的内置函数名称。这可能是由于 SQL Server 2008
猜你喜欢
  • 2014-03-21
  • 2012-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-16
  • 1970-01-01
相关资源
最近更新 更多