Sql server 如何计算每个月的数量,然后在同一select语句中取其平均值

Sql server 如何计算每个月的数量,然后在同一select语句中取其平均值,sql-server,tsql,sql-server-2012,average,Sql Server,Tsql,Sql Server 2012,Average,在如下情况下,如何计算每月总平均数?: 我们有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-

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

我们有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

也许是这样的

示例

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
返回


1.5是什么的平均数?每年每月的索赔平均数。所以我们总共有9个claimId/6个不同的月=1.5John,太神奇了!在我真正的查询中,我只有
NULL
,有时是
DateClosed
。是否有任何方法可以对只有
DateClosed
count(ClaimID)
?@Oleg进行空值更新。希望这有帮助。哦!你改为计算了
DateClosed
!因为我尝试了案例陈述,但我仍然计算了
ClaimID
。非常感谢。