我正在处理一个非常棘手的SQL查询,我想将其转换为LINQ。
你认为有可能吗?
WITH ConditionalChecks AS (
SELECT c.ItemId FROM ConditionalProperties c, Properties p
WHERE c.PropertyId = p.Id AND c.IsChecked = 1 AND (
(p.SystemName = 'eatable') OR
(p.SystemName = 'diy')
)
),
ConditionalCount AS (
SELECT ItemId, Count(*) AS NumTrue FROM ConditionalChecks
GROUP BY ItemId
),
ItemResult AS (
SELECT * FROM ConditionalCount c, Items i
WHERE c.ItemId = i.Id
)
SELECT * FROM ItemResult
WHERE NumTrue = 2
任何提示都表示赞赏!
答案 0 :(得分:3)
LINQ可以轻松聚合这样的查询。
var conditionalChecksQuery =
from c in db.ConditionalProperties
where c.IsChecked == 1 // or 'true', if boolean
join p in db.Properties on c.PropertyId equals p.Id
where p.SystemName == "eatable" || p.SystemName == "diy"
select c.ItemId;
var conditionalCountQuery =
from c in conditionalChecksQuery
group c by c.ItemId into cGrouped
select new { ItemId = cGrouped.Key, NumTrue = cGrouped.Count() };
var itemResultQuery =
from c in conditionalCountQuery
join i in db.Items on c.ItemId equals i.Id
select new { Item = i, NumTrue = c.NumTrue };
var finalQuery =
from result in itemResultQuery
where result.NumTrue == 2
select result;
答案 1 :(得分:1)
我认为这样的事情应该有效
Select * FROM (
Select c.ItemID, Count(*) As NumTrue
FROM ConditionalProperties c, Properties p
WHERE c.PropertyId = p.Id AND c.IsChecked = 1 AND (
(p.SystemName = 'eatable') OR
(p.SystemName = 'diy')
GROUP BY ItemID
) AS ConditionalCount
INNER JOIN Items AS I
ON ConditionalCount.ItemID = I.id
WHERE ConditionalCount.NumTrue = 2
这是SQL,不知道为什么我认为你在做LINQ,并且想要SQL,但这是一种更简单的SQL形式,应该与你的多个查询完全相同。