如何将以下 SQL 查询(CTE LEFT JOINED 与另一个表)编写为 Lambda 或查询表达式?
WITH Hours as
(
SELECT 0 As Hour
UNION ALL
SELECT Hour + 1
FROM Hours
WHERE Hour + 1 < 24
)
SELECT Hours.Hour, COALESCE(Revenue, 0) FROM Hours
LEFT JOIN
(
SELECT DATEPART(hh, TableDate) As Hour, SUM(Revenue) Revenue FROM MyTable
GROUP BY DATEPART(hh, TableDate)
) c
ON
c.Hour = Hours.Hour
我知道我可以 GroupJoin 和 SelectMany 来完成 LEFT JOIN,但我不知道从哪里开始表示查询的 CTE 部分。我是否必须创建一个静态表来使用 lambda 或查询表达式来完成此操作?
- 编辑 -
所以我最终得到了这个(为了便于阅读,我更喜欢查询表达式而不是 lambda):
var revenue = (
from range in Enumerable.Range(0, 23)
join conv in db.MyTable on range equals conv.TableDate.Hour into c
from d in c.DefaultIfEmpty()
group d by range into g
select new { Hour = g.Key, Revenue = g.Sum(e => e == null ? 0.0 : e.Revenue), }
)