我有一个数据集,我每天都有一些观察结果。我想按日期对它们进行分组,然后取每日每日总和的平均值(以SQL为单位)。
用于按天分组的SQL看起来像这样并且有效。
"SELECT Date, Sum(Margin) FROM [OpenPositions] GROUP BY Date"
我已尝试使用以下代码在一个SQL中执行预期的查询。
"SELECT Datepart(week, Date),
Avg(avgmargin)
FROM (SELECT Datepart(year, Date) Year,
Datepart(week, Date) Week,
Sum(Margin) sum
FROM [OpenPositions]
GROUP BY Datepart(year, Date),
Datepart(week, Date)"
但这不起作用(没有显示任何数据)。任何人都可以在我的SQL查询中找到错误,以及如何解决它?
所有帮助表示赞赏。
答案 0 :(得分:0)
试试这个:
Select Datepart(week, Date), Avg(avgmargin) from (
SELECT Date, Sum(Margin) AS Margin FROM [OpenPositions] GROUP BY Date)
Group By Datepart(week, Date)
编辑#2
试试这个:
Select TBL.week, Avg(TBL.margin) from (
SELECT Datepart(week, Date) as week ,Datepart(day, Date), Sum(Margin) AS margin
FROM [OpenPositions] GROUP BY Datepart(week, Date),Datepart(day, Date)) as TBL
Group By TBL.week
@ calc16关于你的回复,为什么不这样做:
Select TBL.week, Avg(TBL.margin) from
(SELECT Datepart(week, Date) as week, Date, Sum(Margin) AS margin FROM[OpenPositions]
GROUP BY Datepart(week, Date), Date) as TBL
Group By TBL.week
您应该在内部查询中将年份添加到组中。
Select TBL.week, , Avg(TBL.margin) from
(SELECT Datepart(week, Date) as week,Datepart(year, Date) as year, Date, Sum(Margin) AS margin FROM[OpenPositions]
GROUP BY Datepart(week, Date), Datepart(year, Date) ,Date) as TBL
Group By TBL.week, TBL.year