-1
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 ..

我想指定这个顺序,以便让我的 UI 正确..

4

2 回答 2

4

你可以这样写orderby:

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;
于 2013-05-01T09:02:07.550 回答
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)));

至于排序,这将在数据库服务器上进行选择,在本地机器上进行排序。有了这么少量的数据,我希望这比使生成的 SQL 复杂化更快。

于 2013-05-01T09:25:40.907 回答