我可以按年份选择总和,这很容易。
就像这样。
var query = from t in ctx.SomeDataEntity
group t by t.DateAdded.Year into g
select new
{
Year = g.Year,
Total = g.Sum(t => t.SomeColumn1) +
g.Sum(t => t.SomeColumn2) +
g.Sum(t => t.SomeColumn3) +
g.Sum(t => t.SomeColumn4)
};
但是,如何按月过滤数据? 简单地将t.DateAdded.Year替换为t.DateAdded.Month并不容易,因为t.DateAdded.Month是1,2,3,...,12。 我需要的是格式为2014-01,2014-02,...,2014-12。
答案 0 :(得分:1)
您可以按年份和月份进行分组:
var query = from t in ctx.SomeDataEntity
group t by new
{
Year = t.DateAdded.Year,
Month = t.DateAdded.Month
} into g
select new
{
MonthAndYear = g.Key.Year + "-" + g.Key.Month,
Total = g.Sum(t => t.SomeColumn1) +
g.Sum(t => t.SomeColumn2) +
g.Sum(t => t.SomeColumn3) +
g.Sum(t => t.SomeColumn4)
};
答案 1 :(得分:0)
您可以按月和年分组:
var query = from t in ctx.SomeDataEntity
group t by new { Month = t.DateAdded.Month, Year = t.DateAdded.Year } into g
select new
{
Year = g.Key.Year,
Month = g.Key.Month,
Total = g.Sum(t => t.SomeColumn1) +
g.Sum(t => t.SomeColumn2) +
g.Sum(t => t.SomeColumn3) +
g.Sum(t => t.SomeColumn4)
};
答案 2 :(得分:0)
试试这个:
var query = from t in ctx.SomeDataEntity
group t by new { t.DateAdded.Year, t.DateAdded.Month} into g
select new
{
Year = g.Key.Year,
Month = g.Key.Month,
Total = g.Sum(t => t.SomeColumn1) +
g.Sum(t => t.SomeColumn2) +
g.Sum(t => t.SomeColumn3) +
g.Sum(t => t.SomeColumn4)
};