简体   繁体   English

SQL 查询到 LINQ 表达式 - Entity Core Framework 3 + SQL Server

[英]SQL query to LINQ expression - Entity Core Framework 3 + SQL Server

DECLARE @thirtyDaysAgo DATETIME = getdate()-30

SELECT 
sum(case when CreatedWhen >= @thirtyDaysAgo then 1 else 0 end) lessThan30,
sum(case when CreatedWhen < @thirtyDaysAgo then 1 else 0 end) Greaterthan30
FROM ThisAwesomeTable

Cannot figure out how to convert this to a fluent query.无法弄清楚如何将其转换为流畅的查询。

The intent is to count the number of rows that were created more than 30 days ago and also count the number of rows that were created within the last 30 days in the same query.目的是计算 30 天前创建的行数,并计算同一查询中过去 30 天内创建的行数

You need to use the singleton GroupBy trick:您需要使用单例GroupBy技巧:

var ans = ThisAwesomeTable.GroupBy(r => 1)
                          .Select(rg => new {
                              lessThan30 = rg.Sum(r => r.CreatedWhen >= thirtyDaysAgo ? 1 : 0),
                              GreaterThan30 = rg.Sum(r => r.CreatedWhen < thirtyDaysAgo ? 1 : 0)
                          });

Note that EF Core 3 generates exactly the same SQL as listed for this query.请注意,EF Core 3 生成的 SQL 与为此查询列出的 SQL 完全相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM