SQL 新人入門 (從基礎框架走起)
阿新 • • 發佈:2018-12-29
SQL 新人入門 (從基礎框架走起)SQL語句最基礎框架
select 欄位 from 表名
以下語句皆在該基礎上加內容,假設表名為table
①如果想搜尋表內所有內容
select * from table
②搜尋多個欄位
select city,country from table
③同時搜尋兩個表的內容,假設兩個表裡id欄位內容相同
select
a.city,
a.country,
b.number
from table1 a
left join table2 b
on a.id=b.id
④以city分組
select
a.city,
a.country,
b.number
from table a
from table b
group by city
⑤以city升序排序
select
a.city,
a.country,
b.number
from table a
from table b
group by city
order by city
降序
select
a.city,
a.country,
b.number
from table a
from table b
group by city
order by city desc
⑥類似資料透視表功能,計算城市數量
select
a.city,
a.country,
b.number,count(1) //括號裡面的1代表以第一列為計數標準。
from table a
from table b
group by city
order by city
⑦計算數量的基礎上去重
select
a.city,
a.country,
b.number,count(distinct positionId) //distinct 後面跟具有唯一標識,可用來做去重標準
from table a
from table b
group by city
order by city
⑧多維聚合
select
a.city,
a.country,
b.number,count(distinct positionId)
from table a
from table b
group by city,country //group by 新增多個欄位,它將以多維的形式進行資料聚合
order by city
⑨限制條件,數量500以上的城市
select
a.city,
count(distinct positionId)
from table a
group by city having count(distinct positionId) >= 500
order by city
⑩巢狀子查詢
select * from
(select city ,count (distinct positionId) as counts from table
group by city ) as t1 //as 可命名錶名
where counts >=500