我正在尝试生成一个查询,该查询获取每个给定月份内发生日期的条目数。我希望生成的查询的SQL形式如下:
SELECT
DatePart(Year, [t1].[StartTime]) as Year,
DatePart(Month, [t1].[StartTime]) as Month,
Count(*) as 'Visits',
Sum([t1].[PageCount]) as 'Total Pageviews'
FROM
[MyDatabase] [t1]
GROUP BY
DatePart(Year, [t1].[StartTime]),
DatePart(Month, [t1].[StartTime])
我尝试了以下Linq2DB代码:
var query = from table in dataContext.MyDataContext(tablePath)
group table by new { table.StartTime.Year, table.StartTime.Month} into grp
select new { Month = grp.Key.Month, Year = grp.Key.Year,
TotalVisitors = grp.Count(),
TotalPageviews = grp.Sum(table2 => table2.PageCount) };
但是由此生成的SQL查询是
-- SqlServer.2008 --
SELECT
[t1].[StartTime],
Count(*) as [c1],
Sum([t1].[PageCount]) as [c2]
FROM
[MyDatabase] [t1]
GROUP BY
DatePart(Year, [t1].[StartTime]),
DatePart(Month, [t1].[StartTime]),
[t1].[StartTime]
为什么[t1]。[StartTime]而不是月份或年份?为什么它会在最后加上[t1]。[StartTime]进行分组?如何使用Linq2DB生成上面的SQL查询?
答案 0 :(得分:2)
请对 Sql.AsSql 函数使用以下解决方法。我们正试图解决这个长期存在的问题。
<div style="width:125px;height:300px;overflow:auto;margin:auto;">
<div style="width:75px;height:75px;margin:auto;margin-top:10px;margin-bottom:10px;background-color:red;"></div>
<div style="width:75px;height:75px;margin:auto;margin-top:10px;margin-bottom:10px;background-color:blue;"></div>
<div style="width:75px;height:75px;margin:auto;margin-top:10px;margin-bottom:10px;background-color:pink;"></div>
<div style="width:75px;height:75px;margin:auto;margin-top:10px;margin-bottom:10px;background-color:green;"></div>
<div style="width:75px;height:75px;margin:auto;margin-top:10px;margin-bottom:10px;background-color:yellow;"></div>
<div style="width:75px;height:75px;margin:auto;margin-top:10px;margin-bottom:10px;background-color:orange;"></div>
<div style="width:75px;height:75px;margin:auto;margin-top:10px;margin-bottom:10px;background-color:black;"></div>
<div style="width:75px;height:75px;margin:auto;margin-top:10px;margin-bottom:10px;background-color:brown;"></div>
<div style="width:75px;height:75px;margin:auto;margin-top:10px;margin-bottom:10px;background-color:purple;"></div>
<div style="width:75px;height:75px;margin:auto;margin-top:10px;margin-bottom:10px;background-color:grey;"></div>
</div>