1

如何将以下 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), }
                  )
4

2 回答 2

2

很难准确地说出你的模型在 linq 中是什么,但可能是这样的:

var Enumerable.Range(0,23)
      .Join(MyTable.GroupBy(x => x.TableDate.Hour())
             .Select(g => new { hour = g.Key, rev = g.Revenue.Sum() },
            h => h,
            g => g.hour,
            (h , g) -> new { hour = h, revenue = g.rev });
于 2013-11-03T00:23:44.337 回答
1

等效的 linq 查询表达式

from a in Enumerable.Range(0, 24)
join b in Mytables on a equals b.TableDate.Hour into c
from d in c.DefaultIfEmpty()
group d by a into g
select new {h = g.Key, s = g.Sum(e => e == null ? 0.0m : e.Revenue)}
于 2013-11-03T00:51:03.360 回答