从以下SQL编写LINQ需要一些帮助。 主要问题是双重分组。 我已经堆叠在第二个分组
中了group by s.[e-year], s.[e-month]
不知道如何实施。
非常感谢。
select s.[e-year], s.[e-month], count(s.projectid) 'projects entranced',
---------------------------------------------
(select count(subquery.CustomerTypeID) from
(select count(ap.ProjectID) as 'count', c.CustomerTypeID FROM Logging_ProjectsEntrances] pe
inner join users u on pe.userid = u.userid
inner join Companies c on u.CompanyId = c.CompanyID
inner join AssignedProjects up on pe.ProjectID = up.ProjectID
inner join Projects p on up.ProjectID = p.ProjectID
where ap.ProductID = 1 and year(pe.EntranceDate) = s.[e-year] and MONTH(pe.entrancedate) = s.[e-month] and c.CustomerTypeID = 2
group by ap.ProjectID, c.CustomerTypeID) subquery
group by subquery.CustomerTypeID
)
--------------------------------------------
from
(
select YEAR(pe.EntranceDate) as 'e-year', MONTH(pe.EntranceDate) as 'e-month', up.ProjectID as 'projectid'
FROM Logging_ProjectsEntrances pe
inner join AssignedProjects ap on pe.ProjectID = ap.ProjectID
inner join Projects p on ap.ProjectID = p.ProjectID
where ap.ProductID = 1
group by year(pe.EntranceDate), month(pe.EntranceDate), ap.ProjectID
) as s
group by s.[e-year], s.[e-month]
order by s.[e-year] desc , s.[e-month] desc
答案 0 :(得分:1)
将SQL转换为LINQ查询理解:
DISTINCT
,TOP
等)转换为应用于整个LINQ查询的函数。new {
... }
)。.DefaultIfEmpty()
执行另一个来模拟左连接。COALESCE
。IN
翻译为.Contains()
,将NOT IN
翻译为!
... Contains()
SELECT *
必须替换为select range_variable或者连接,一个包含所有范围变量的匿名对象。SELECT
字段必须替换为select new {
... }
,以创建包含所有所需字段或表达式的匿名对象。FULL OUTER JOIN
。注意:您的SQL查询使用SQL技巧(SELECT x
... GROUP BY x
)执行等效的DISTINCT
,应该使用它,因为它表达意图更多清楚。
因此,对于您的SQL查询:
var subq = (from pe in projectsEntrances
join ap in assignedProjects on pe.ProjectID equals ap.ProjectID
join p in projects on ap.ProjectID equals p.ProjectID
where ap.ProductID == 1
select new { e_year = pe.EntranceDate.Year, e_month = pe.EntranceDate.Month, ap.ProjectID }).Distinct();
var ans = from s in subq
group s by new { s.e_year, s.e_month } into sg
orderby sg.Key.e_year descending, sg.Key.e_month descending
select new { sg.Key.e_year, sg.Key.e_month, ProjectsEntranced = sg.Count() };