【发布时间】:2011-11-21 06:37:36
【问题描述】:
我前段时间为一个工具构建了一个 SQL 查询,我正在 MVC 中重新制作该工具并使用 LINQ to Entities。
我似乎不知道如何通过按工时及其测试价值对我的汽车进行加权来对我的品牌列表进行排序。
这是我在旧工具中的 SQL 查询:
SELECT Brand.ID, SUM(Car.EstManHours) - SUM(Car.EstManHours) * CAST(AVG(1.00 * TestingStatus.Value) AS DECIMAL(9 , 2)) / 100 AS Weighting
FROM TestingStatus INNER JOIN Car ON TestingStatus.ID = Car.StatusID
INNER JOIN Team ON Car.TeamID = Team.TeamID
RIGHT OUTER JOIN Brand
LEFT OUTER JOIN SubCategory ON Brand.ID = SubCategory.BrandID ON Car.SubCategoryID = SubCategory.ID
WHERE (Car.IsPunted == 'False')
GROUP BY Brand.YearID, Brand.FeatID
HAVING (Brand.YearID = @BrandYearID)
ORDER BY Weighting DESC
我已经尝试过了,但是无论我将降序还是升序放在列表中实际上并没有改变,它保持按 Id 排序:
var brands = (from b in _context.Brands
join s in _context.SubCategorys on f.Id equals s.BrandId
join c in _context.Cars on s.Id equals c.SubCategoryId
where (f.YearId == yearId && c.IsPunted == false)
orderby (c.ManHoursEst - (c.ManHoursEst * c.TestingStatu.Value / 100)) descending
select b).Distinct().ToList();
非常感谢有关此转换的帮助!
谢谢。
编辑:
我现在正试图让 order by 和 group by 正常工作。 以下查询列出了大量重复项并且没有正确排序,因为我认为我的权重没有正确完成。
var brands = (from b in _context.Brands
join s in _context.SubCategorys on f.Id equals s.BrandId
join c in _context.Cars on s.Id equals c.SubCategoryId
where (f.YearId == yearId && c.IsPunted == false)
let weighting = c.ManHoursEst - (c.ManHoursEst * c.TestingStatu.Value / 100)
orderby weighting descending
group b by b.Id).SelectMany(x=>x).ToList();
有什么想法吗?
【问题讨论】:
-
您的原始查询正在执行分组 - 您的 LINQ 查询不是。
-
@LanFeusT :为了可读性,我会使用“let”子句来计算权重,然后按“权重”排序。它不会改变性能或输出,只是带有公式的 order by 子句伤害了我的眼睛:-P
-
@Tipx 绝对是个好主意! ^^ 谢谢会做。