1

我有第一个产生正确结果的查询。我需要的是我需要将值的总和添加为按 . 分组的最后一列surveyid。我无法插入Sum(c.value)第一个查询,因为它是一个聚合函数。我有正确的查询作为下面的第二个查询。我知道有枢轴功能,但不确定是否可以在这里使用。我确实意识到会有重复,但没关系。

'第一次查询

SELECT 
   A.PATIENTID, B.STUDENTNUMBER, c.surveyid, 
   convert(varchar, A.CreatedDate, 107), 
   C.QuestionID, C.Value, D.Question
FROM 
   dbo.Survey A, dbo.Patient B, [dbo].[SurveyQuestionAnswer] C, [dbo].[LookupQuestions] D
WHERE 
   A.PATIENTID = B.ID 
   and c.SurveyID = A.ID 
   and c.QuestionID = d.ID 
   and c.questionid <> 10
ORDER BY 
   A.PATIENTID

'第二次查询

select 
    c.surveyid,SUM(c.value) as scores
from 
    dbo.SurveyQuestionAnswer c
group by 
    c.SurveyID 
order by 
    SurveyID '---not important
4

2 回答 2

4

如果添加子句,则可以使用。在这种情况下:SUMOVER

SELECT 
   A.PATIENTID, B.STUDENTNUMBER, c.surveyid, 
   convert(varchar, A.CreatedDate, 107), 
   C.QuestionID, C.Value, D.Question,
   SUM(c.Value) OVER(PARTITION BY c.surveyid) scores
FROM 
   dbo.Survey A
INNER JOIN dbo.Patient B
    ON A.PATIENTID = B.ID 
INNER JOIN [dbo].[SurveyQuestionAnswer] C
    ON c.SurveyID = A.ID
INNER JOIN [dbo].[LookupQuestions] D
    ON c.QuestionID = d.ID 
WHERE 
   c.questionid <> 10
ORDER BY 
   A.PATIENTID
于 2013-07-04T20:59:51.137 回答
0

你可以使用这样的东西:

SELECT 
   s.PATIENTID, p.STUDENTNUMBER, sqa.surveyid, 
   CONVERT(varchar, s.CreatedDate, 107), 
   sqa.QuestionID, sqa.Value, lq.Question,
   Scores = (SELECT SUM(Value) FROM dbo.SurveyQuestionAnswer s2 WHERE s2.SurveyID = s.ID)
FROM 
   dbo.Survey s
INNER JOIN
   dbo.Patient p ON s.PatientID = p.ID
INNER JOIN
   [dbo].[SurveyQuestionAnswer] sqa ON sqa.SurveyID = s.ID
INNER JOIN 
   [dbo].[LookupQuestions] lq ON sqa.QuestionID = lq.ID
WHERE 
   sqa.questionid <> 10
ORDER BY 
   s.PATIENTID

通过使用子查询,SUM(...)您应该能够将该总和作为单个值获得,并且您不需要使用任何分组函数

于 2013-07-04T21:00:05.507 回答