按计算字段过滤和排序

时间:2016-06-03 04:17:13

标签: c# sql-server linq tsql

我有一个SQL查询我试图转换为LINQ for C#但我无法解决如何对计算字段进行排序和过滤。

from p in PartRevisions
where (p.Inactive == 0)
where (p.LastCost != p.AvgCost) || (p.LastCost != p. StandardCost) 
select new {
    PartID = p.PartID,
    Desc = p.ShortDescription,
    AvgCost = p.AvgCost,
    LastCost = p.LastCost,
    last_avg = 100* ( (p.AvgCost > p.LastCost) ? 
     ((p.LastCost > 0) ? (p.AvgCost - p.LastCost) / p.LastCost : (decimal?)null):
     ((p.AvgCost> 0) ? (p.LastCost - p.AvgCost ) / p.AvgCost : (decimal?)null))
}

查询执行正常但我需要在计算字段last_avg中添加where子句和sort子句 即last_avg> 10 orderby last_avg下降。

这是SQL中的相同查询

SELECT  PartID, PartRevisionID, LastCost, AverageCost, 
CASE WHEN LastCost < AvgCost THEN (AvgCost - LastCost) / NULLIF (LastCost, 0) ELSE (LastCost - AvgCost) / NULLIF (AvgCost, 0) END AS Last_Avg, 
FROM  PartRevisions
WHERE (LastCost <> AvgCost OR LastCost <> StandardCost) AND (Inactive == 0) 
ORDER BY Last_Avg DESC

有谁知道如何实现这个目标?

2 个答案:

答案 0 :(得分:0)

你可以这样做:

(from p in PartRevisions
where (p.Inactive == 0)
where (p.LastCost != p.AvgCost) || (p.LastCost != p. StandardCost) 
select new {
    PartID = p.PartID,
    Desc = p.ShortDescription,
    AvgCost = p.AvgCost,
    LastCost = p.LastCost,
    last_avg = 100* ( (p.AvgCost > p.LastCost) ? 
     ((p.LastCost > 0) ? (p.AvgCost - p.LastCost) / p.LastCost : (decimal?)null):
     ((p.AvgCost> 0) ? (p.LastCost - p.AvgCost ) / p.AvgCost : (decimal?)null))
})
.OrderByDescending(pr => pr.last_avg);

答案 1 :(得分:0)

好的,这是有效的。对于那些想知道我在这里找到答案的人。 Calculating Intermediate Values

@SuppressWarnings("unchecked")
Collection<File> myCollection = FileUtils.listFiles(...);