如何将以下SQL查询(CTE LEFT JOINED与另一个表)作为Lambda或Query Expression编写?
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), }
)
答案 0 :(得分: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 });
答案 1 :(得分: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)}