如何理解group by語句

參考文章:spa

  https://blog.csdn.net/hao1066821456/article/details/69556644.net

如何實現一對多關係,獲得一行多列的顯示方式:code

  group by能夠理解爲,group以後生成一個虛擬表,group的字段對應的只有一行,而其餘的字段整合成一行,再把這些字段進行聚合如count、sum、max、min。blog

  下面的例子理解爲:如A選項,對每個大行中的小行進行case when,而後對結果進行取max,不是A選項的都是空值,取max就獲得A選項的實際值。io

select eq.id,eq.content,eqo.code,eqo.optioncontent from ExamQuestion eq
right join ExamQuestionOption  eqo 
on eq.id=eqo.qid
order by eqo.qid,eqo.code

select id
,MAX(case code when 'A' then optioncontent else '' end) A
,MAX(case code when 'B' then optioncontent else '' end) B
,MAX(case code when 'C' then optioncontent else '' end) C
,MAX(case code when 'D' then optioncontent else '' end) D
 from (
select eq.id,eq.content,eqo.code,eqo.optioncontent from ExamQuestion eq
right join ExamQuestionOption  eqo 
on eq.id=eqo.qid
) T 
group by id
order by id

 

相關文章
相關標籤/搜索