iT邦幫忙

2025 iThome 鐵人賽

DAY 6
0
Software Development

我所不知道的PostgreSQL 30天系列 第 6

Day 6: 基本語法介紹 - Aggregate Functions

  • 分享至 

  • xImage
  •  

除了前幾天介紹幾個比較基本的CRUD功能,PostgreSQL也有提供Aggregate Function,讓使用者可以對資料做一些運算,結合分群的功能,也能夠統計一些數據。舉例來說,如果我們想要知道 address 這張table有多少筆資料,可以用 count() 加總。

SELECT count(*) FROM address

如果想要統計有多少筆地址分布在各個城市,可以用 GROUP BY 並搭配 count() 做加總,還可以使用 max() 找出地址的最後更新時間。

SELECT address.city_id, count(*), max(address.last_update) FROM address
    GROUP BY address.city_id


此外,還可以用 FILTER 下條件,過濾不要統計哪些資料,舉例來說,我們想要排除沒有電話號碼的地址,可以在 count(*) 後面加上 FILTER(WHERE phone != '')

SELECT address.city_id, count(*) FILTER(WHERE phone != ''), max(address.last_update) FROM address
    GROUP BY address.city_id

city_id = 576 做驗證,有加上 FILTER(WHERE phone != '')count(*) 統計出來只有一筆資料。

沒有加上條件,會有兩筆資料。


上一篇
Day 5: 基本語法介紹 - Update 和 Delete
下一篇
Day 7: Check Constraints簡介
系列文
我所不知道的PostgreSQL 30天30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言