1. 程式人生 > >My SQL Case_3: 根據旅遊局資料練習My SQL語句(前6題)

My SQL Case_3: 根據旅遊局資料練習My SQL語句(前6題)

練習1. 從dw_complain_total這個表中列出201509的投訴總量及男女分別投訴多少?
# 練習1. 從dw_complain_total這個表中列出201509的投訴總量及男女分別投訴多少?
# 注意:as用法,時間函式用法, 還有求的是總量

select sum(comp_total) as c_t, sum(male_comp_total) as m_ct, sum(female_comp_total) as f_ct, datetime 
from dw_complain_total 
where DATE_FORMAT(datetime, '%Y%m') = '201509'
;

在這裡插入圖片描述

練習2. 從dw_complain_total這個表中列出201509各區域的投訴量。
# 練習2. 從dw_complain_total這個表中列出201509各區域的投訴量。
# 注意:group by area,記住在前面select欄位的時候還要有一個相同欄位area

select sum(comp_total) as c_t, area
from dw_complain_total 
where DATE_FORMAT(datetime, '%Y%m') = '201509'
group by area;

在這裡插入圖片描述

練習3. 從dw_complain_total這個表中列出2015年09月份北京的 投訴處理率;保留兩位小數點,加上百分號
# 練習3. 從dw_complain_total這個表中列出2015年09月份北京的 投訴處理率;保留兩位小數點,加上百分號
# 注意:保留小數點用的是round()函式;百分號想到用字串拼接concat

# 思路遞進
# 初步:
select comp_total as c_t, area
from dw_complain_total 
where DATE_FORMAT(datetime, '%Y%m') = '201509' and area = '北京';

# 優化後:
select sum(comp_processed_total)/sum(comp_total) as c_t, area
from
dw_complain_total where DATE_FORMAT(datetime, '%Y%m') = '201509' and area = '北京'; # 再優化後: select concat(round(sum(comp_processed_total)/sum(comp_total)*100, 2), '%') as c_t, area from dw_complain_total where DATE_FORMAT(datetime, '%Y%m') = '201509' and area = '北京';

在這裡插入圖片描述

練習4. 2015年9月份北京的投訴型別及投訴數量
# 練習4. 2015年9月份北京的投訴型別及投訴數量
# 注意:尋找另一個表,雙表聯立,找到外來鍵,group by什麼想清楚肯定是跟著挑選出來的欄位的,如何按照降序排列,

SELECT
b.zw_name,
sum(a.complain_total)as comptotal
from dw_complain_tslx a JOIN dm_tslx b on a.tslx_code = b.zd_name
where DATE_FORMAT(datetime,'%Y%m')='201509' and area = '北京'
group by b.zw_name order by comptotal desc limit 9

在這裡插入圖片描述

練習5 列出2015年9月份投訴來源省top 10,還可以限定是投訴北京的(不是來源)
# 練習5 列出2015年9月份投訴來源省top 10,還可以限定是投訴北京的(不是來源)
# 注意:還是得選擇專業的表;,group by什麼想清楚肯定是跟著挑選出來的欄位的
-- select 
-- sum(comp_total) as c_t, area
-- from dw_complain_total
-- where DATE_FORMAT(datetime, '%Y%m') = 201509
-- group by area order by comp_total desc limit 10;

SELECT
area_ly as province,
sum(complain_total) as compltotal
from dw_complain_tsly
where DATE_FORMAT(datetime,'%Y%m')= 201509
GROUP BY area_ly
ORDER BY sum(complain_total) desc
limit 10

在這裡插入圖片描述

練習6 列出最近3年的投訴量(也就是從此時開始,最近36個月的投訴量每個月列出來,ps因為最近12個月沒有資料)
# 練習6 列出最近3年的投訴量(也就是從此時開始,最近36個月的投訴量每個月列出來,ps因為最近12個月沒有資料)
# 注意:時間函式還是要記住格式, between now() interval and now()

SELECT
DATE_FORMAT(datetime,'%Y%m') as ttime,
SUM(comp_total) as compaintotal
from dw_complain_total
WHERE datetime BETWEEN DATE_ADD(now(),INTERVAL -3 year) and NOW() 
GROUP BY ttime

在這裡插入圖片描述