【问题标题】:How to count number per month and then take average of it in same select statement如何计算每月的数量,然后在同一个选择语句中取平均值
【发布时间】:2019-06-21 21:35:31
【问题描述】:

以下情况如何计算每月总平均数?:

我们有 9 个claimID。所以平均是 9/ 6 个不同的月份 = 1.5

DECLARE @TestTable TABLE (claimid int, DateClosed datetime)

INSERT INTO @TestTable  
VALUES (111, '01-01-2018'), (222, '01-03-2018'), (333, '01-12-2018'),
       (444, '07-03-2018'), (555, '08-15-2018'), (666, '09-13-2018'),
       (777, '04-03-2019'), (888, '05-01-2019'), (999, '07-01-2018'),
       (1000, NULL), (1100, NULL), (1200, NULL)

SELECT 
    ClaimID,
    CAST(DateClosed AS DATE) AS DateClosed,
    COUNT(ClaimID) CountClaimID,
    COUNT(claimid) OVER (PARTITION BY MONT(DateClosed), YEAR(DateClosed)) AS CountPerMonth
FROM 
    @TestTable
GROUP BY 
    ClaimID, DateClosed

【问题讨论】:

  • 1.5 是什么的平均值?
  • 每年每月的 ClaimID 平均数。所以我们总共有 9 个 claimId / 6 个不同的月份 = 1.5

标签: sql-server tsql sql-server-2012 average


【解决方案1】:

大概是这样的

示例

SELECT ClaimID
       ,cast(DateClosed AS date) AS DateClosed
       ,count(ClaimID) CountClaimID
       ,count(claimid) OVER ( PARTITION BY Month(DateClosed), year(DateClosed)) AS CountPerMonth
       ,case when DateClosed is null then 0 else count(DateClosed) over () / (select 0.0+count(distinct left(cast(DateClosed as date),7)) from @TestTable) end AS TotalAverage
FROM   @TestTable
GROUP  BY ClaimID,DateClosed

退货

【讨论】:

  • 约翰,太棒了!在我真正的查询中,唯一的事情是 NULL 有时是 DateClosedcount(ClaimID) 有没有办法只有DateClosed
  • @Oleg 针对 NULL 更新。希望这会有所帮助。
  • 哦!你数了DateClosed!因为我尝试了案例陈述,但我仍然计算了ClaimID's。谢谢
猜你喜欢
  • 2020-04-10
  • 1970-01-01
  • 2014-01-24
  • 1970-01-01
  • 2021-01-08
  • 2019-04-19
  • 2021-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多