mysql 橫表和縱錶轉換

(1)表tb1有以下數據: sql

姓名                     語文                        數學                    物理 code

張三                       68                           89                        99 數學

李四                      90                            66                         78 io

如今要求寫出查詢語句獲得以下查詢結果 class

name                    subject                       score select

張三                       語文                           68
張三                       數學                           89
張三                       物理                            99
李四                       語文                            90
李四                      數學                            66
李四                       物理                            78

sql語句以下: sql語句

select 姓名 as name,'語文' as subject,語文 as score from tb1
union
select 姓名 as name,'數學' as subject,數學 as score from tb1
union
select 姓名 as name,'物理' as subject,物理 as score from tb1
order by name



或者: nio

select * from(
select 姓名 as name,'語文' as subject,語文 as score from tb1
union
select 姓名 as name,'數學' as subject,數學 as score from tb1
union
select 姓名 as name,'物理' as subject,物理 as score from tb1
)tb
order by name



(2)tb2表有以下數據: 數據

name              subject                  score 查詢

張三               語文                       74
張三                英語                      88
張三                物理                       90
李四                語文                      88
李四                英語                      67
李四                物理                        95

經過查詢獲得以下數據:

姓名         語文                  英語                     物理

張三          74                   88                        90
李四           88                    67                        95

sql語句以下:

select name as '姓名',
max(case subject when '語文' then score else 0 end) 語文,
        max(case subject when '英語' then score else 0 end) 英語,
        max(case subject when '物理' then score else 0 end)物理
from tb2
group by name



如今要求寫出查詢語句獲得以下結果:

姓名         語文                  英語                     物理            總分                平均分

張三          74                    88                        90               252                    84
李四           88                    67                        95                250                    83.33

sql:

select name '姓名',
max(case subject when '語文' then result else 0 end) 語文,
max(case subject when '物理' then result else 0 end) 物理,
max(case subject when '英語' then result else 0 end)英語,
sum(result) as 總分,
avg(result) as 平均分
from tb
group by name
相關文章
相關標籤/搜索