SQL到LINQ的问题
本文关键字:问题 LINQ SQL | 更新日期: 2023-09-27 17:53:30
我有一些SQL返回两列,X列和Y列:
SELECT TOP (100) PERCENT
dbo.SurveyAnswer.QuestionAnswer AS [Y],
COUNT(dbo.SurveyAnswer.QuestionAnswer) AS [X]
FROM
dbo.SurveyAnswer
INNER JOIN dbo.SurveyQuestion ON
dbo.SurveyAnswer.QuestionID = dbo.SurveyQuestion.QuestionID
INNER JOIN dbo.FieldAgentCall ON
dbo.SurveyAnswer.JobId = dbo.FieldAgentCall.JobId AND
dbo.SurveyAnswer.ObjectiveId = dbo.FieldAgentCall.ObjectiveID AND
dbo.SurveyAnswer.AgentId = dbo.FieldAgentCall.AgentID
INNER JOIN dbo.SurveyQuestionaire ON
dbo.FieldAgentCall.JobId = dbo.SurveyQuestionaire.JobId and
dbo.SurveyQuestion.QuestionaireID = dbo.SurveyQuestionaire.QuestionaireID and
WHERE
(dbo.SurveyQuestion.QuestionNo = 9) AND (dbo.SurveyQuestion.QuestionaireID = 1) AND
dbo.SurveyAnswer.QuestionAnswer <>'NA'
GROUP BY
dbo.SurveyAnswer.QuestionAnswer
ORDER BY
[Y]
SQL搜索一系列表并返回问题的所有答案和分组,因此结果类似于。
X | Y
No | 234
Yes | 43
SQL工作得很好,我得到了没有问题的工作,由于查询的长度和不同的参数被发送进来,查询得到了一个无法管理的大小,并决定它的时间成为LINQ。
所以我试图得到基本的LINQ工作,以获得结果,但相当新的LINQ,我不能完全得到它的工作
var query = (from answers in db.SurveyAnswerModels.ToList()
join question in db.SurveyQuestion.Where(i => i.QuestionID == 9 && i.QuestionaireID == 1).ToList() on answers.QuestionID equals question.QuestionID
join questionnaire in db.SurveyQuestionnaire.ToList() on question.QuestionaireID equals questionnaire.QuestionaireID
join fieldagent in db.FieldAgentCall.ToList() on questionnaire.JobId equals fieldagent.JobId
group answers.QuestionAnswer by answers.QuestionAnswer into results
select new { X = results.Count(), Y = results });
我得到的结果是X的计数错误,Y数据不是组
[{"Xs":2814,"Ys":["No","No","No","No",
虽然这是错误的数量,因为我认为我还没有添加正确的参数,所以这是我可以排序的东西,但我遇到的主要问题是组,我试图尽可能多地复制它,但失败了。
"No"应该只是一个"No",加上有多少个"No",计数器显示有2,814个"No",我只需要它说一次"No"。
任何建议也会很好,比如我哪里做错了。
试试这个:
var query = (from answers in db.SurveyAnswerModels
join question in db.SurveyQuestion on answers.QuestionID equals question.QuestionID
join questionnaire in db.SurveyQuestionnaire on question.QuestionaireID equals questionnaire.QuestionaireID
join fieldagent in db.FieldAgentCall on questionnaire.JobId equals fieldagent.JobId
where question.QuestionID == 9 && question.QuestionaireID == 1
group answers.QuestionAnswer by answers.QuestionAnswer into results
select new { Count = results.Count(), Answer = results.Key });
与您的差异:
- ToLists()被删除了(这最好是不必要的,最坏的情况是会搞砸c#表达式到sql的转换)
- 将Where()移到底部(不必要,但更容易遵循)
- 选择的结果。钥匙作为答案。关键是达到结果组的"分组"值。
我认为3。