select*From Orders as O innerjoin [Order Details] OD On O.OrderID = OD.OrderID //合併條件
說明 :
將orders及order details 兩張表作合併(join),分別命名為O及OD
步驟三:
1 2 3 4 5
select*From Orders as O innerjoin [Order Details] OD On O.OrderID = OD.OrderID innerjoin [Customers] C On C.CustomerID = O.CustomerID //合併條件
說明:
on作為合併條件,圖中是將O的OrderId與OD的OrderId做合併條件
步驟四:
1 2 3 4 5
select C.CompanyName, UnitPrice*Quantity*(1-Discount) From Orders as O innerjoin [Order Details] OD On O.OrderID = OD.OrderID innerjoin [Customers] C On C.CustomerID = O.CustomerID
select C.CompanyName, UnitPrice*Quantity*(1-Discount) as LineTotal From Orders as O innerjoin [Order Details] OD On O.OrderID = OD.OrderID innerjoin [Customers] C On C.CustomerID = O.CustomerID
select O.OrderID,C.CompanyName, UnitPrice*Quantity*(1-Discount) as LineTotal From Orders as O innerjoin [Order Details] OD On O.OrderID = OD.OrderID innerjoin [Customers] C On C.CustomerID = O.CustomerID
說明:
查詢 O 的OrderID、Companyname、LineTotal (注意: OrderID需指定為哪張表的OrderID,若無指定會報錯誤訊息: 模稜兩可 )
步驟七:
1 2 3 4 5 6 7
select O.OrderID,C.CompanyName, UnitPrice*Quantity*(1-Discount) as LineTotal From Orders as O innerjoin [Order Details] OD On O.OrderID = OD.OrderID innerjoin [Customers] C On C.CustomerID = O.CustomerID
Groupby CompanyName
說明:
錯誤原因:OrderID 非Groupby條件或總合運算所以必須拿掉
1 2 3 4 5 6
select C.CompanyName, SUM( UnitPrice*Quantity*(1-Discount) ) as Total From Orders as O innerjoin [Order Details] OD On O.OrderID = OD.OrderID innerjoin [Customers] C On C.CustomerID = O.CustomerID Groupby CompanyName
說明:
刪除OrderID即可正常執行,Group by 為群聚條件,依指定條件合併,將多筆record合併成單一record
步驟八:排序(由大到小)
1 2 3 4 5 6 7
select C.CompanyName, SUM( UnitPrice*Quantity*(1-Discount) ) as Total From Orders as O innerjoin [Order Details] OD On O.OrderID = OD.OrderID innerjoin [Customers] C On C.CustomerID = O.CustomerID Groupby CompanyName Orderby Total Desc//反序
說明:
Order by作為排序條件,Desc為反排序
步驟九:挑出前幾筆資料(在select後面加上”Top 數字”)
1 2 3 4 5 6 7
select Top 1 C.CompanyName, SUM( UnitPrice*Quantity*(1-Discount) ) as Total From Orders as O innerjoin [Order Details] OD On O.OrderID = OD.OrderID innerjoin [Customers] C On C.CustomerID = O.CustomerID Groupby CompanyName Orderby Total Desc
createview dbo.TopCustomers as select C.CompanyName, SUM( UnitPrice*Quantity*(1-Discount) ) as Total From Orders as O innerjoin [Order Details] OD On O.OrderID = OD.OrderID innerjoin [Customers] C On C.CustomerID = O.CustomerID Groupby CompanyName
select*From TopCustomers
說明:
Create view 建立view,alter view修改view。
1
select Top 10*From TopCustomers //從View中挑選前10筆資料
建立有排序(大到小)且取前10筆資料
1 2 3 4 5 6 7 8 9
createview dbo.Top10Customers as select Top 10 C.CompanyName, SUM( UnitPrice*Quantity*(1-Discount) ) as Total From Orders as O innerjoin [Order Details] OD On O.OrderID = OD.OrderID innerjoin [Customers] C On C.CustomerID = O.CustomerID Groupby CompanyName Orderby Total Desc
1
select*from Top10Customers
clustered index 查詢: WHERE比對
完整比對
1 2
select*from Products WHERE ProductName ='Ipoh Coffee'