在SQL中使用组合后的行

时间:2015-05-12 09:52:03

标签: sql sql-server

我创建了像

这样的查询
SELECT COUNT(CurrentSlideId) AS attempts,
       CurrentSlideId,
       UserLessonProgressId,
       IsHint
FROM  UserAnswers
WHERE (UserID = 169494)
  and UserLessonProgressId=218629 
GROUP BY UserLessonProgressId, CurrentSlideId, IsHint
ORDER BY UserLessonProgressId, CurrentSlideId

以上查询的输出类似于

enter image description here

现在我想将最后两行合并为一行,如

尝试= 2 currentSlideId = 19328 UserLessonProgressId = 218629且 IsHint = 1

2 个答案:

答案 0 :(得分:2)

保持您的查询,但MAX(IsHINT)并从GROUP BY

中删除该列
SELECT COUNT(*) AS attempts,
       CurrentSlideId,
       UserLessonProgressId,
       MAX(IsHint)
FROM  UserAnswers
WHERE UserID = 169494
  and UserLessonProgressId = 218629 
GROUP BY CurrentSlideId, UserLessonProgressId
ORDER BY CurrentSlideId, UserLessonProgressId

答案 1 :(得分:0)

                        SELECT        COUNT(CurrentSlideId) AS attempts, CurrentSlideId, UserLessonProgressId, max(case when IsHint=1 then 1 else 0 end) hint
                        FROM            UserAnswers
                        WHERE        (UserID = 169494) and UserLessonProgressId=218629 
                        GROUP BY UserLessonProgressId, CurrentSlideId
                        ORDER BY UserLessonProgressId,CurrentSlideId