2010年7月1日 星期四

SQL第1堂課 資料查詢


順便來紀錄一下Red上課的內容, 相關連結資料來源 WebDesign

資料查詢



練習1
請寫出一個SQL, 使用日期函數及Between語法, 從USER_LIST table, 找出生日(birth)欄位月份在08到09之間, 並且部門代碼(dept_code)為ITBD開頭的人員, 顯示下列四個欄位
dept_codeemp_idemp_cnamebirth

解答:
select dept_code, emp_id, emp_cname, birth
from USER_LIST
where month(birth) between '8' and '9' and dept_code like 'ITBD%'


練習2
請寫出一個SQL, 找出USER_LIST table, 中文姓名(emp_cname)姓'王',並且姓名第2個字為'俊'或'國',顯示下列四個欄位:(此題目限制只能有一個where condition like)
dept_codeemp_idemp_cnamebirth

解答:

select dept_code,emp_id,emp_cname,birth
from User_List
where emp_cname
like('王[俊國]%')


練習3
A公司在AUS以及AUT各有一套薪資系統, 請使用下列Table,寫一個table join + union的SQL, 並寫出執行的Result
Result
DEPT_NAMEEMP_NAMEMONTHSalary_AMT


AUT tables

Employee_AUT
EMP_IDEMP_NAMEDEPT_ID
1AlisaA
2CharlesB

DEPT_AUT
DEPT_IDDEPT_NAME
AIT
BSales


Salary_AUT
EMP_IDMonthSalary_AMT
1201005100
1201006105
2201005120
2201006125


AUS tables

Employee_AUS
EMP_IDEMP_NAMEDEPT_ID
1JasonA
2CKC

DEPT_AUS
DEPT_IDDEPT_NAME
AIT
CMFG

Salary_AUS
EMP_IDMonthSalary_AMT
1201005100
1201006105
2201005120
2201006125


解答:

select d.DEPT_NAME,  e.EMP_NAME,  s.MONTH,  s.Salary_AMT
from Employee_AUT e
inner join DEPT_AUT d
on e.DEPT_ID = d.DEPT_ID
inner join Salary_AUT s
on e.EMP_ID = s.EMP_ID
UNION
select d.DEPT_NAME,  e.EMP_NAME,  s.MONTH,  s.Salary_AMT
from Employee_AUS e
inner join DEPT_AUS d
on e.DEPT_ID = d.DEPT_ID
inner join Salary_AUS s
on e.EMP_ID = s.EMP_ID


Result
DEPT_NAMEEMP_NAMEMONTHSalary_AMT
ITAlisa201005100
ITAlisa201006105
SalesCharles201005120
SalesCharles201006125
ITJason201005100
ITJason201006105
MFGCK201005120
MFGCK201006125


練習4
請使用left outer join ,join下列四個table: order_mst, order_dtl, product, customer, 列出所有customer的資訊,如result的顯示欄位,並將結果填入result表格

Order_mst
order_no customer_ID ship_addr order_date sales
1 2 xx 10/1/1 red
2 1 aa 10/1/1 charles
 

order_dtl
order_no product_ID qty
1 a 10
1 b 20
2 a 100
2 c 200

Product
product_ID Product_name unit_price
a LCD panel 1000
b mouse 50
c keyboard 100
 
customer
Customer_ID Customer_name
1 Acer
2 BenQ
3 Sony
 
result
Customer_name Order_no ship_addr order_date product_name unit_price qty total_amt


 
解答:

select c.customer_name, t.order_no, t.ship_addr,  t.order_date ,p.product_name, p.unit_price, d.qty, d.qty * p.unit_price as  total_amt 
from customer c
left outer join order_mst t 
on  t.customer_ID = c.customer_ID
left outer join order_dtl d
on t.order_no =  d.order_no
left outer join product p
on d.product_ID =  p.product_ID

Customer_name Order_no ship_addr order_date product_name unit_price qty total_amt
BenQ 1 xx 10/1/1 LCD panel 1000 10 10000
BenQ 1 xx 10/1/1 mouse 50 20 1000
Acer 2 aa 10/1/1 LCD panel 1000 100 100000
Acer 2 aa 10/1/1 keyboard 100 200 20000
Sony null null null null null null null


感謝Red提供教學~

沒有留言:

張貼留言

Related Posts with Thumbnails