gpt4 book ai didi

c# - 另一个 LINQ Pivot 问题——将 SQL 脚本转换为 LINQ

转载 作者:行者123 更新时间:2023-11-30 17:24:52 26 4
gpt4 key购买 nike

SO 上已经有一些关于 LINQ 枢轴的问题,虽然其中有几个问题概述了我的确切问题,但我无法成功地将它们转化为有效的解决方案。我觉得这主要是因为我的表中有联接。

因此,为了所有喜欢解决问题的 LINQ 爱好者的利益,这里有另一个难题供您解决。请通过将以下 SQL 存储过程脚本转换为 LINQ 来帮助我(并赢得一些声望点和我的尊重):

ALTER PROCEDURE [dbo].[GetTimesheetForWeekById]
@timesheetid int,
@begindate VarChar(20),
@enddate VarChar(20)
AS
BEGIN

SELECT T.TaskName,
SUM(
case DATEPART(weekday, TE.StartTime)
WHEN 1 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END
) AS Sunday,
SUM(
case DATEPART(weekday, TE.StartTime)
when 2 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END
) AS Monday,
SUM(
case DATEPART(weekday, TE.StartTime)
when 3 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END
) AS Tuesday,
SUM(
case DATEPART(weekday, TE.StartTime)
when 4 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END
) AS Wednesday,
SUM(
case DATEPART(weekday, TE.StartTime)
when 5 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END
) AS Thursday,
SUM(
case DATEPART(weekday, TE.StartTime)
when 6 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END
) AS Friday,
SUM(
case DATEPART(weekday, TE.StartTime)
when 6 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END
) AS Saturday

FROM Tasks T
INNER JOIN TimeEntries TE on T.TaskID = TE.TaskID
WHERE TE.StartTime BETWEEN
(CONVERT(datetime, @begindate, 103)) AND (CONVERT(datetime, @enddate, 103))
AND TE.TimesheetID = @timesheetid
GROUP BY T.TaskName
END

最佳答案

好吧,假设外键有一个对象表示,类似于:

        int timesheetId = ...
DateTime start = ..., end = ...
var qry = from timeEntry in ctx.TimeEntries
let date = timeEntry.StartTime.Date
where timeEntry.TimesheetId == timesheetId
&& date >= start
&& date <= end
group timeEntry by timeEntry.Task.TaskName into grp
select new {
TaskName = grp.Key,
Monday = grp.Where(x => x.StartTime.DayOfWeek == DayOfWeek.Monday).Count(),
Tuesday = grp.Where(x => x.StartTime.DayOfWeek == DayOfWeek.Tuesday).Count(),
Wednesday = grp.Where(x => x.StartTime.DayOfWeek == DayOfWeek.Wednesday).Count(),
Thursday = grp.Where(x => x.StartTime.DayOfWeek == DayOfWeek.Thursday).Count(),
Friday = grp.Where(x => x.StartTime.DayOfWeek == DayOfWeek.Friday).Count()
};

不幸的是,一些细节取决于 SQL 提供程序 - 即哪些函数(如 DayOfWeek 等)可以成功映射为 TSQL。如果您遇到问题,请告诉我...

关于c# - 另一个 LINQ Pivot 问题——将 SQL 脚本转换为 LINQ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/348900/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com