从过去三天开始,我一直在做一项任务。我尝试将一个 sql 查询转换为基于“将列转换为行”称为数据透视表的 linq。
我的 SQL 查询如下。
SELECT project_name
,SUNDAY
,MONDAY
,TUESDAY
,WEDNESDAY
,THRUSDAY
,FRIDAY
,SATURDAY
FROM
(
SELECT project_name
,personnel_name
,DATENAME(dw, report_date) AS day_name
,SUM(hours) AS HOURS
FROM [TimeSheet]
INNER JOIN [ProjectMaster]
ON [TimeSheet].[project_id] = [ProjectMaster].[project_id]
INNER JOIN [Personnel]
ON [TimeSheet].[personnel_id] = [Personnel].[personnel_id]
WHERE report_date BETWEEN getdate() - 7 AND getdate()
GROUP BY project_name, personnel_name, DATENAME(dw, report_date)
) sourceQuery PIVOT (SUM(hours)
FOR day_name IN
(SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THRUSDAY,FRIDAY,SATURDAY)) AS pvt
到目前为止我所做的将其转换为 linq 如下!!!
var before = DateTime.Now.AddDays(-7);
DateTime firstSunday = new DateTime(1753, 1, 7);
var DayWiseTS = from TSList in objWPFEntities.Timesheets.Include("ProjectMaster").Include("Personnel")
where (TSList.report_date >= before && TSList.report_date <= System.DateTime.Now)
select new { TSList.ProjectMaster.project_name, TSList.Personnel.personnel_name, TSList.report_date, TSList.hours } into sourceQuery
group sourceQuery by new { sourceQuery.project_name, sourceQuery.personnel_name, sourceQuery.report_date, sourceQuery.hours } into pvt
select new
{
projectname = pvt.Key.project_name,
Sunday = (EntityFunctions.DiffDays(firstSunday, pvt.Key.report_date.Value) % 7 == 0 ? pvt.Sum(g => g.hours) : 0),
Monday = (EntityFunctions.DiffDays(firstSunday, pvt.Key.report_date.Value) % 7 == 1 ? pvt.Sum(g => g.hours) : 0),
Tuesday = (EntityFunctions.DiffDays(firstSunday, pvt.Key.report_date.Value) % 7 == 2 ? pvt.Sum(g => g.hours) : 0),
Wednesday = (EntityFunctions.DiffDays(firstSunday, pvt.Key.report_date.Value) % 7 == 3 ? pvt.Sum(g => g.hours) : 0),
Thrusday = (EntityFunctions.DiffDays(firstSunday, pvt.Key.report_date.Value) % 7 == 4 ? pvt.Sum(g => g.hours) : 0),
Friday = (EntityFunctions.DiffDays(firstSunday, pvt.Key.report_date.Value) % 7 == 5 ? pvt.Sum(g => g.hours) : 0),
Saturday = (EntityFunctions.DiffDays(firstSunday, pvt.Key.report_date.Value) % 7 == 6 ? pvt.Sum(g => g.hours) : 0)
};
我在两个查询中都得到了结果,但是在 sql 中,我得到了我需要的完美结果,但是在 linq 中,我没有得到所需的数据作为 sql。
sql结果::
LINQ结果::
我认为,在我的 linq 查询中,我未能按小时分组!!
谁可以帮我这个事??