iT邦幫忙

0

postgresql 資料庫語法的應用

請教大家
通常會使用下列的語法來抓取一段日期區間的資料
select * from table where date1 between date1 and date2
但因為想應用在postgresql中依照所處的月份來自動抓出該月份的資料,在postgresql中有無函數可讓日期自動切換與抓取呢?
謝謝

souda iT邦好手 1 級 ‧ 2017-01-20 13:58:12 檢舉
請參考postgresql官方網站說明1. https://www.tutorialspoint.com/postgresql/postgresql_date_time.htm
2. https://www.postgresql.org/docs/9.2/static/datatype-datetime.html
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
海綿寶寶
iT邦大神 1 級 ‧ 2017-01-20 14:09:36
最佳解答
SELECT * FROM table1
WHERE DATE_PART('MONTH', date1) = DATE_PART('MONTH', NOW())
4
一級屠豬士
iT邦新手 2 級 ‧ 2017-01-20 14:27:33

create table ithelp170120 (
  id serial primary key
, cdate date not null
, val text not null
);

insert into ithelp170120 values
(default, date '2016-12-25', '上個月'),
(default, date '2017-01-01', '這個月'),
(default, date '2017-01-10', '這個月'),
(default, date '2017-01-31', '這個月'),
(default, date '2017-02-05', '下個月'),
(default, date '2016-01-10', '去年的今月');

要找出這個月,可以利用 current_date 先得到今天日期

select current_date;
+------------+
|    date    |
+------------+
| 2017-01-20 |
+------------+
(1 row)

再搭配 date_trunc 擷取日期部分函數,選擇月,會得到本月初的 timestamp,
再轉型為日期型態,得到月初日期.

select date_trunc('month', current_date)::date;
+------------+
| date_trunc |
+------------+
| 2017-01-01 |
+------------+
(1 row)

接下來再利用 interval 型態,加一個月減一天,轉型為日期,得到月底日期.

select (date_trunc('month', current_date) + interval '1 month' - interval '1 day')::date;
+------------+
|    date    |
+------------+
| 2017-01-31 |
+------------+

結合搭配使用

select *
  from ithelp170120
 where cdate between date_trunc('month', current_date)::date
   and (date_trunc('month', current_date) + interval '1 month' - interval '1 day')::date;
   
+----+------------+--------+
| id |   cdate    |  val   |
+----+------------+--------+
|  2 | 2017-01-01 | 這個月 |
|  3 | 2017-01-10 | 這個月 |
|  4 | 2017-01-31 | 這個月 |
+----+------------+--------+
(3 rows)
--
若是使用僅 date_part 函數

select *
  from ithelp170120
 where date_part('month', cdate) = date_part('month', now());   

+----+------------+------------+
| id |   cdate    |    val     |
+----+------------+------------+
|  2 | 2017-01-01 | 這個月     |
|  3 | 2017-01-10 | 這個月     |
|  4 | 2017-01-31 | 這個月     |
|  6 | 2016-01-10 | 去年的今月 |
+----+------------+------------+
(4 rows)

月份會轉成數字擷取出來, 資料若是有跨年,就會有怪東西出現了. 
ektrontek iT邦研究生 1 級 ‧ 2017-01-23 21:49:46 檢舉

感謝幫忙,滿有幫助的日期查詢應用資訊

我要發表回答

立即登入回答