我有一个Part
列表,其中包含DateTime
注册到Database
时的@{
var shiftChangeTime = new TimeSpan(16, 0, 0);
<table>
<tr>
@*This is my general average*@
<td>Number of part/hour</td>
@{
var avg = Model.GroupBy(x => ((DateTime)x.ScanTime).TimeOfDay.Hours)
.Average(x => x.Count());
<td>@(Math.Round(avg, 2))</td>
}
</tr>
<tr>
@*This is my day average*@
<td>Number of part/hour</td>
@{
var avgDay = Model.GroupBy(x => ((DateTime)x.ScanTime).TimeOfDay < shiftChangeTime, y => ((DateTime)y.ScanTime).TimeOfDay.Hours)
.Average(x => x.Count());
<td>@(Math.Round(avgDay, 2))</td>
}
</tr>
<tr>
@*This is my night average*@
<td>Number of part/hour for night shift</td>
@{
var avgNight = Model.GroupBy(x => ((DateTime)x.ScanTime).TimeOfDay > shiftChangeTime, y => ((DateTime)y.ScanTime).TimeOfDay.Hours)
.Average(x => x.Count());
<td>@(Math.Round(avgNight, 2))</td>
}
</tr>
</table>
}
值。
我想显示每小时白班和每夜班次登记的人数。
我试图将我的普通平均值的逻辑基于这两个值
Declare @String varchar(max) = 'FinancialYear=47faabe1-f6aa-e411-941e-00155d010d10&FinancialPeriod=4dfaabe1-f6aa-e411-941e-00155d010d10&Branch=eefb631b-4e1b-e611-9436-00155d010d10&Branch=369d0919-edaa-e411-941e-00155d010d10&Branch=e9a7dc75-f9aa-e411-941e-00155d010d10&Branch=cb3a3c67-f9aa-e411-941e-00155d010d10&Department=00000000-0000-0000-0000-000000000000&Department=adb0f49a-4f1b-e611-9436-00155d010d10&Department=487c64ae-4f1b-e611-9436-00155d010d10&Department=4c9b0919-edaa-e411-941e-00155d010d10'
Select Seq =Key_PS
,Item =Substring(Key_Value,1,charindex('=',Key_Value)-1)
,Value =Substring(Key_Value, charindex('=',Key_Value)+1,100)
From [dbo].[udf-Str-Parse](@String,'&')
我目前坚持按小时划分昼/夜转换的逻辑。
现在它将我的总人数分成两部分。
关于如何进行的任何想法?
答案 0 :(得分:1)
上述代码存在的问题是,在GroupBy
天/夜班后,您还需要按Hour
进行分组才能达到小时平均值。
这可以显示白天/夜班中一小时内的平均部分:
List<Part> Model = new List<Part>
{
new Part{ ScanTime = new DateTime(2016,1,1,1,0,0) },
new Part{ ScanTime = new DateTime(2016,1,1,4,0,0) },
new Part{ ScanTime = new DateTime(2016,1,1,4,0,0) },
new Part{ ScanTime = new DateTime(2016,1,1,4,0,0) },
new Part{ ScanTime = new DateTime(2016,1,1,4,0,0) },
new Part{ ScanTime = new DateTime(2016,1,1,7,0,0) },
new Part{ ScanTime = new DateTime(2016,1,1,12, 0,0) },
new Part{ ScanTime = new DateTime(2016,1,1,17,0,0) },
new Part{ ScanTime = new DateTime(2016,1,1,19,0,0) },
new Part{ ScanTime = new DateTime(2016,1,1,23,0,0) },
};
var shiftChangeTime = new TimeSpan(12, 0, 0);
var result = Model.GroupBy(x => x.ScanTime.TimeOfDay < shiftChangeTime ? "Day" : "Night")
.Select(g => new
{
Shift = g.Key,
Average = g.GroupBy(item => item.ScanTime.Hour,
(key, group) => new { Hour = key, Amount = group.Count() })
.Average(y => y.Amount)
}).ToList();
如果您不希望2 GroupBy
,则另一个选项是首次使用Where
来保留特定班次的记录,然后是其他选项:
var dayAverage = Model.Where(x => x.ScanTime.TimeOfDay < shiftChangeTime)
.GroupBy(item => item.ScanTime.Hour,
(key, group) => new { Hour = key, Amount = group.Count() })
.Average(y => y.Amount);