这是一个ASP.NET MVC项目。目前我有一张表:
Skill Date Offered Answered Abandoned
SampleSkill1 12/1/2013 53585 52549 1036
SampleSkill2 12/1/2013 7170 6997 173
SampleSkill1 11/1/2013 45635 45189 446
SampleSkill2 11/1/2013 6481 6378 103
SampleSkill1 10/1/2013 54838 54208 630
SampleSkill2 10/1/2013 7361 7235 126
我正在尝试将数据放在表格中:
SampleSkill1
Type Oct Nov Dec
Offered 53585 52549 1036
Answered 45635 45189 446
Abandoned 54838 54208 630
我能得到的最接近的是做这样的事情:
var StatsList = db.Stats.Where(c => c.Skill == "SampleSkill1").ToList();
var OfferedStatsQuery = StatsList
.GroupBy(c => c.Skill)
.Select(g => new StatsPivot {
Skill = g.Key,
Oct = g.Where(c => c.Date.Month == 10).Sum(c => c.Offered),
Nov = g.Where(c => c.Date.Month == 11).Sum(c => c.Offered),
Dec = g.Where(c => c.Date.Month == 12).Sum(c => c.Offered)
});
var AnsweredStatsQuery = StatsList
.GroupBy(c => c.Skill)
.Select(g => new StatsPivot {
Skill = g.Key,
Oct = g.Where(c => c.Date.Month == 10).Sum(c => c.Answered),
Nov = g.Where(c => c.Date.Month == 11).Sum(c => c.Answered),
Dec = g.Where(c => c.Date.Month == 12).Sum(c => c.Answered)
});
我确信这不是做这样的事情的最佳/正确方法,但我是LINQ的新手。关于如何有效实现预期结果的任何建议?
答案 0 :(得分:0)
我的建议是在数据库端(可能通过存储过程)而不是在代码中执行。不太确定这个建议是否对你有限制,因为那时你的工作变得非常简单,高效,你也可以获得很多选择。请查看链接here以获取类似问题的答案。
希望这有帮助。
答案 1 :(得分:0)
当您使用Linq进行此类操作时。修改代码并不容易。所以尝试从DB端做这些事情..
参见以下示例..
http://www.codeproject.com/Tips/500811/Simple-Way-To-Use-Pivot-In-SQL-Query
http://blogs.msdn.com/b/spike/archive/2009/03/03/pivot-tables-in-sql-server-a-simple-sample.aspx