我正在尝试将SQL查询转换为LINQ,但是我需要利用HAVING Count(Distinct),这在LINQ中无法实现,而且我似乎找不到替代方法来获得相同的结果
SELECT
B.BranchCode ,
B.BranchName ,
rv.ENGINEER ,
CONVERT ( DATE, rv.VISITDATE ) [Date] ,
CONVERT ( TIME, rv.STARTTIME ) [Start] ,
COUNT ( DISTINCT rv.VISITID ) V
FROM
dbo.ltbl_Branch AS B
INNER JOIN dbo.tbl_contract AS C ON C.BranchCode = B.BranchCode
INNER JOIN dbo.tbl_repair_order AS r ON r.CONTRACT = C.Contract
INNER JOIN dbo.tbl_repair_visit AS rv ON rv.ORDERID = r.ORDERID
WHERE
CONVERT ( DATE, rv.VISITDATE ) BETWEEN '2019-02-01'
AND '2019-02-01'
AND ISNULL ( rv.FromHHT, 0 ) = 0
GROUP BY
B.BranchCode ,
B.BranchName ,
rv.ENGINEER ,
CONVERT ( DATE, rv.VISITDATE ) ,
CONVERT ( TIME, rv.STARTTIME )
HAVING
COUNT ( DISTINCT rv.VISITID ) > 1
上面是我要转换的SQL查询,到目前为止,我拥有的LINQ查询在下面
from b in Ltbl_Branches
join c in Tbl_contracts on b.BranchCode equals c.BranchCode
join r in Tbl_repair_orders on c.Contract equals r.CONTRACT
join rv in Tbl_repair_visits on r.ORDERID equals rv.ORDERID
where rv.VISITDATE >= DateTime.Today.AddDays(-123)
&& rv.VISITDATE <= DateTime.Today.AddDays(-122)
&& rv.FromHHT == false
group b by new { b.BranchCode, b.BranchName, rv.ENGINEER, rv.VISITDATE,
rv.STARTTIME } into g
where g.Count() > 1
select new {
BranchCode = g.Key.BranchCode,
BranchName = g.Key.BranchName,
Engineer = g.Key.ENGINEER,
Date = g.Key.VISITDATE,
Time = g.Key.STARTTIME,
V = g.Count()
}
我正在努力在linq上工作的原因是Whileing Count(DISTINCT rv.VISITID)> 1,我认为其余代码都按预期工作。
我正在从网络上的数据库中提取数据,由于它具有重复的条目,因此2月1日目前只是一个随机日期,而从.AddDays(-123)来自的日期开始,当前是123 。 这两个查询返回不同的结果,SQL查询返回的计数为170,而我的LINQ查询仅返回98。