C# 需要linq查询以获取特定的结果集
如果有人可以在这里帮助准备这个linq查询 下表数据如下:C# 需要linq查询以获取特定的结果集,c#,linq,C#,Linq,如果有人可以在这里帮助准备这个linq查询 下表数据如下: category question answer user a1 q1 3 u1 a1 q1 5 u2 a1 q2 3 u2 a2 q3 3 u3 a2 q3 2 u4 a3 q4 9 u3 a3
category question answer user
a1 q1 3 u1
a1 q1 5 u2
a1 q2 3 u2
a2 q3 3 u3
a2 q3 2 u4
a3 q4 9 u3
a3 q5 8 u7
a3 q5 2 u9
我需要的结果如下:
按类别、问题、结果分组(有以下三种情况的分组)
因此,对于每个类别、每个问题,需要将结果分成三种形式(按答案分组(你不需要按答案分组。而是过滤并计算答案,如下所示:
from t in db.Table
group t by new {t.Category, t.Question} into g
order by g.Category
select new
{
CategoryName = t.FirstOrDefault().Category, //might be required to handle null here
Question = t.FirstOrDefault().Question, //might be required to handle null here
TotalCount = t.Count(),
AnsLessEqual3 = t.Where(d => d.Answer<=3).Count(),
Ans5 = t.Where(d => d.Answer = 5).Count(),
Ans789 = t.Where(d => d.Answer = 7 || d.Answer = 8 || d.Answer = 9).Count()
}
数据库表中的t的
按新的{t.Category,t.Question}将t分组到g中
按g.类别排序
选择新的
{
CategoryName=t.FirstOrDefault().Category,//可能需要在此处处理null
Question=t.FirstOrDefault().Question,//可能需要在此处处理null
TotalCount=t.Count(),
ANSLESQUAL3=t.Where(d=>d.答案d.答案=5).Count(),
Ans789=t.Where(d=>d.Answer=7 | | d.Answer=8 | | d.Answer=9).Count()
}
虽然上面的查询没有经过测试,但我相信它会让您快速开始前进。谢谢格式化。我也尝试过同样的方法。非常感谢。当我尝试在
foreach
循环中迭代结果时,它会给我下面的错误。文本数据类型无法选择为独立的,因为它不可比较。
请确认石斑鱼类。
SELECT
Category, Question,
Count(Ans),
CASE
WHEN Ans = 9 OR Ans = 8 OR ans=7 THEN '9 or 8 or 7'
WHEN Ans = 5 THEN '5'
WHEN Ans <= 3 THEN '<=3'
END as 'ResultGroup'
FROM
SurveyQuestions
GROUP BY
Category, Question, Ans
ORDER BY
Question
from t in db.Table
group t by new {t.Category, t.Question} into g
order by g.Category
select new
{
CategoryName = t.FirstOrDefault().Category, //might be required to handle null here
Question = t.FirstOrDefault().Question, //might be required to handle null here
TotalCount = t.Count(),
AnsLessEqual3 = t.Where(d => d.Answer<=3).Count(),
Ans5 = t.Where(d => d.Answer = 5).Count(),
Ans789 = t.Where(d => d.Answer = 7 || d.Answer = 8 || d.Answer = 9).Count()
}