gpt4 book ai didi

sql-server - 按月/年计算平均值

转载 作者:行者123 更新时间:2023-12-03 09:34:34 26 4
gpt4 key购买 nike

我正在尝试计算每月的平均记录数,但下面的示例代码无法正常工作。

有人能看出我做错了什么吗?我检查了其他一些问题,例如 SQL Server - monthly avg of count但这对我不起作用。

Create Table #TestData
(
DateCreated datetime,
Number int
)

Insert into #TestData
(
DateCreated,
Number
)
SELECT
'26 Nov 2018',
'10'
UNION
SELECT
'26 Nov 2018',
'11'
UNION
SELECT
'27 Nov 2018',
'10'
UNION
SELECT
'28 Nov 2018',
'11'
UNION
SELECT
'29 Nov 2018',
'20'
UNION
SELECT
'30 Nov 2018',
'35'
UNION
SELECT
'01 Dec 2018',
'35'
UNION
SELECT
'02 Dec 2018',
'40'
UNION
SELECT
'02 Dec 2018',
'75'

select
month,
year,
cnt,
avg(cnt) as avg
from
(
select
MONTH(DateCreated) AS [month],
YEAR(DateCreated) AS [year],
count(*) as cnt
from
#TestData
group by
MONTH(DateCreated),
YEAR(DateCreated)
) agg
group by
cnt,
month,
year

drop table #TestData

最佳答案

根据我们在评论中的对话,您似乎想要每个月的每日记录计数的平均值 - 以下是对问题代码的一个小修改,以实现这一点:

select 
MONTH(DateCreated) As month,
YEAR(DateCreated) As year,
avg(cast(cnt as float)) as avg -- cast as float otherwise you'll get an integer result
from
(
select
CAST(DateCreated As Date) AS DateCreated,
count(*) as cnt
from
#TestData
group by
CAST(DateCreated As Date) -- group by days
) agg
group by
MONTH(DateCreated),
YEAR(DateCreated)

关于sql-server - 按月/年计算平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53985025/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com