我有一个具有以下结构的表:
| Column Name | Type |
|-------------|--------------- |
| ProjectId | INT |
| StartDate | INT |
| Amount | DECIMAL(12, 2) |
StartDate
是INT
,但它实际上代表一天,格式为YYYYMMDD
。
该表存储项目的每日数值(仅存储工作日,没有星期日或星期六),如下所示:
| ProjectId | StartDate | Amount |
|-----------|-----------|--------|
| 1 | 20140926 | 0.5 |
| 1 | 20140929 | 0.5 |
| 1 | 20140930 | 0.8 |
| 1 | 20141001 | 1 |
| 1 | 20141002 | 1 |
| 1 | 20141003 | 0.5 |
| 2 | 20141001 | 0.6 |
| 2 | 20141002 | 0.5 |
获得每个项目的平均月度值的最有效方法是什么?我使用EF 6(DbContext
方法)和SQL Server 2012?我正在寻找使用Linq-to-Entities的解决方案。
理想的结果是这样的:
| ProjectId | StartDate | Amount |
|-----------|-----------|--------|
| 1 | 20140926 | 0.6 |
| 1 | 20141001 | 0.83 |
| 2 | 20141001 | 0.55 |
我有一个解决方案,但我不确定它是否最佳:
var results = dbContext.ProjectValues
.GroupBy(pv =>
new
{
ProjectId = pv.ProjectId,
Year = pv.StartDate.Year,
Month = pv.StartDate.Month,
})
.Select(g =>
new
{
ProjectId = g.Key.ProjectId,
StartDate = g.Min(v => v.StartDate),
Amount = g.Average(v => v.Amount)
})
.ToList();
答案 0 :(得分:1)
您可以GROUP BY
项目ID和月份
由于日期存储为int,因此使用强制转换
SELECT ProjectID,
AVG(Amount) as AverageAmount,
DATEADD(MONTH, DATEDIFF(MONTH,0,CAST(CAST(StartDate AS VARCHAR(12)) AS DATE)), 0)
FROM Table1
GROUP BY ProjectID, DATEADD(MONTH, DATEDIFF(MONTH,0,CAST(CAST(StartDate AS VARCHAR(12)) AS DATE)), 0)