我在sql中有一个像
的查询select ROW_NUMBER() OVER (Order by A.WeekStartDate) as RowNum,
convert(VARCHAR(12), A.WeekStartDate, 106) + ' - ' + convert(VARCHAR(12), A.WeekEndDate, 106) as Date,
sum(Data1) as SumData1, sum(Data2) as SumData2, sum(Data3) as SumData3,
(SUM(Data1) + SUM(Data2)) as OverallSum
from dbo.Weekdays(convert(datetime, @FromDate, 103), convert(datetime, @ToDate, 103)) A
left join TableData T on convert(datetime, T.strDate, 103) between A.WeekStartDate and A.WeekEndDate
group by A.WeekStartDate, A.WeekEndDate
输出如
RowNum Date SumData1 SumData2 OverallSum
---------------------------------------------------------------
1 02/03/2015-08/03/2015 10 8 18
2 09/03/2015-05/03/2015 16 14 30
我正在将其转换为linq。到目前为止,我已经尝试了这个
from wk in Weekdays
from cr in TableData.Where(x => DateTime.Parse(x.CreatedAt) >= DateTime.Parse(wk.WeekStartDay))
.Where(x => DateTime.Parse(x.CreatedAt) <= DateTime.Parse(wk.WeekendDay)).DefaultIfEmpty()
group wk by new { Weekstartday = wk.WeekStartDay, Weekendday = wk.WeekendDay } into wkgrp
select new { RowNum = ++RNum, Day = wkgrp.Key.Weekstartday + " - " + wkgrp.Key.Weekendday };
但是,我无法在select查询中访问TableData
字段来执行求和和其他操作。我想在TableData.date
和weekstartdate
之间基于weekenddate
加入两个表。怎么能在Linq做到这一点?
我提到了How do you left join using "date between" operator in linq?,但那里的答案只使用了我需要其他聚合函数的地方。
答案 0 :(得分:0)
尝试以下查询:
from wk in Weekdays
from cr in TableData.Where(x => DateTime.Parse(x.CreatedAt) >= DateTime.Parse(wk.WeekStartDay))
.Where(x => DateTime.Parse(x.CreatedAt) <= DateTime.Parse(wk.WeekendDay)).DefaultIfEmpty()
group wk by new { Weekstartday = wk.WeekStartDay, Weekendday = wk.WeekendDay } into wkgrp
select new { RowNum = ++RNum, Day = wkgrp.Key.Weekstartday + " - " + wkgrp.Key.Weekendday,
SumData1 = wkgrp.sum(x => x.Data1),
SumData2 = wkgrp.sum(x => x.Data2),
SumData3 = wkgrp.sum(x => x.Data3),
OverallSum = wkgrp.sum(x => x.Data1) + wkgrp.sum(x => x.Data1)
};
答案 1 :(得分:0)
以下查询对我有用。在群组声明中,我必须将表格名称从group wk
更改为group cr
,然后我才能访问选择查询中的字段。
from wk in Weekdays
from cr in TableData
where (DateTime.Parse(wk.WeekStartDay) <= DateTime.Parse(cr.CreatedAt) &&
DateTime.Parse(wk.WeekendDay) >= DateTime.Parse(cr.CreatedAt))
group cr by new { Weekstartday = wk.WeekStartDay, Weekendday = wk.WeekendDay } into wkgrp
orderby DateTime.Parse(wkgrp.Key.Weekstartday) ascending
select new { RowNum = ++RNum, Day = wkgrp.Key.Weekstartday + " - " + wkgrp.Key.Weekendday,
OverallSum = wkgrp.Sum(p => p.Data1) + wkgrp.Sum(p => p.Data2), SumData1 = wkgrp.Sum(p => p.Data1),
SumData2 = wkgrp.Sum(p => p.Data2), SumData3 = wkgrp.Sum(p => p.Data3) }