select Priority,
case Priority
when 'Medium' then (Count(*)* 100 / (Select Count(*) From #tem where Priority = 'Medium'))
when 'High' then (Count(*)* 100 / (Select Count(*) From #tem where Priority = 'High'))
when 'Low' then (Count(*)* 100 / (Select Count(*) From #tem where Priority = 'Low'))
when 'Critical' then (Count(*)* 100 / (Select Count(*) From #tem where Priority = 'Critical'))
end as '% SLM Met'
from #tem where Bool = 'True'
group by Priority
order by
case Priority
WHEN 'Critical' THEN 1
WHEN 'High' THEN 2
WHEN 'Medium' THEN 3
WHEN 'Low' THEN 4
End
我们如何将其转换为linq ..
我想指定这个顺序,以便让我的用户界面正确..
答案 0 :(得分:4)
您可以像这样编写订单:
from x in tbl
orderby (
x.Priority == "Critical" ? 1 :
x.Priority == "High" ? 2 :
x.Priority == "Medium" ? 3 :
x.Priority == "Low" ? 4 : -1 //-1 when none of the above
)
select x;
答案 1 :(得分:2)
使用普通平均值可以简化整个SQL;
SELECT Priority,100*AVG(CASE WHEN Bool='True' THEN 1.0 ELSE 0.0 END)
AS '% SLM Met'
FROM Tem
GROUP BY Priority
order by
case Priority
WHEN 'Critical' THEN 1 WHEN 'High' THEN 2
WHEN 'Medium' THEN 3 WHEN 'Low' THEN 4
End;
......或者,用Linq编写,例如......
var sortArray = new[] {"Critical", "High", "Medium", "Low"};
var result =
(from tem in dbContext.Tem
group tem by tem.Priority
into priorities
select new
{
priority = priorities.Key,
avg = priorities.Average(x => x.Bool == "True" ? 1 : 0)
})
.AsEnumerable()
.OrderBy(x => (Array.IndexOf(sortArray, x.priority)));
对于排序,这将执行数据库服务器上的select和本地计算机上的排序。有了这么少的数据,我希望它比复制生成的SQL更快。