MS SQL Query แบบพื้นฐาน basic สุดๆ
posted on 02 Nov 2009 15:37 by techinnoreview in MITT--ตัวอย่างเท่านั้น การ query ต้องทำตามความเหมาะสมนะจ๊ะ
select
ProductID, (UnitPrice*Quantity)-discount as Grand_total -- ใช้เรียกค่า พร้อมคำนวณไปด้วย และตั้งชื่อมัน
COUNT(*), Max(UnitPrice), Min(UnitPrice), AVG(UnitPrice) -- ใช้สรุปค่าต่างๆ
*
From
[Order Details]
Products
where
ProductID in (20,42) -- หรือ not in ใช้ระบุ
and OrderID <= 10320 -- and และ or หรือ
between 20 and 42 -- เลือกค่าระหว่างเท่าใหร่ถึงเท่าใหร่
like '%20%' -- in case 'a%' คือ a อยู่หน้า '%a' a อยู่หลัง '%a%' a อยู่ที่ไหนก็ตาม
หาหมด เอาไว้ใช้หาพวกชื้อ ใช้ในพวก search algorithm
is null -- is not null ใช้กับพวกที่อณุญาติให้มีค่าว่างได้
Group By
SupplierID -- จับกลุ่มด้วย SupplierID
--การใช้ having
select SupplierID, COUNT(*) as Count,M AX(UnitPrice)
From Products
group by SupplierID
having COUNT(*)>=3
--การใช้ order by ในการเรียงลำดับ
select productID,UnitPrice, Unitsinstock
From Products
Order by UnitPrice -- แบบนี้จะเรียงโดยนับ UnitPrice เป็นหลักจากน้อยไปมาก
Order by -- ใส field [asc|DSC] เช่น UnitPrice desc หรือ ProductID asc, UnitPrice desc
--เลือกแบบเรียงลำดับ + พร้อมทั้ง เรียงจากอันใหม่ก่อน โดยผลจะออกมาแบบสุ่ม
select top 10 ProductID
From Products
order by NEWID()
--เลือกหลาย table หรือเอามา join กันนั่นเอง
select Products.Productid, Products.Productname, categories.categoryname
--เลือกว่าจะแสดงอะไรออกมาบ้าง
from products, categories
-- เลือก มาทั้ง 2 tables
where products.categoryid = categories.categoryid
--เอามาเทียบกันซะ
--* trick ตั้งชื่อเล่น ให้ table เวลาสั่ง From ให้ใช้เป็น products as P, categories as C
และเมื่อสั่ง where ก็จะใช้ P.categoryid = C.categoryid แทนได้เลย
-- Join แบบแท้ๆ (inner join)
select Products.Productid, Products.Productname, categories.categoryname
--เลือกว่าจะแสดงอะไรออกมาบ้าง
from products
Join categories -- จับมันมัดรวมกันซะเลย
on products.categoryid = categories.categoryid
-- left right outer join มากันพร้อมหน้า ถ้างงลองไปอ่านทฤษฎีดู ง่ายๆคือเอาซ้ายหมด ขวาหมด
from products
Left Join categories -- แบบนี้เอา products ไว้หมด
right Join categories -- แบบนี้เอา categories ไว้หมด
outer Join categories -- แบบนี้เอา มาทั้งหมด
on products.categoryid = categories.categoryid
-- view เฉยๆไม่เหมือน select เอาไว้กันมือบอน แก้ไขไม่ได้ และ ประหยัดพลังเครื่องครับผม
-- คลิกขวาที่ views แล้วกด new views เลยครับ จะมี tool ขึ้นมาให้เราใช้
-- ง่ายกว่าตรง อยากได้อะไรก็ใช้ tools ช่วยได้เลย กด add ไปแล้วก็เลือกได้เลยครับ พอเลือกจนพอใจแล้วก็กด เครื่องหมายตกใจหรือ execute ได้เลยครับผ้ม
edit @ 2 Nov 2009 16:50:40 by Auttapong Maesincee