首頁 > 軟體

PGSQL查詢最近N天的資料及SQL語句實現替換欄位內容

2023-03-07 06:04:12

1、用SQL查詢最近N天的資料

思路:先獲取當前的時間,然後更具當前時間去減去對應的天數,就可以得到需要的天數了。然後用這些天數作為條件,然後即可查詢出需要多少天的資料了。

-- 獲取當前時間
SELECT CURRENT_TIMESTAMP;
-- 或
SELECT now();
select CURRENT_TIMESTAMP :: DATE AS "當前日期";
SELECT CURRENT_DATE;
select CURRENT_TIMESTAMP :: TIME AS "當前時間";
SELECT CURRENT_TIME;

最近N天

-- 最近7天
SELECT DATE( T ) AS DAY
FROM
generate_series ( ( CURRENT_TIMESTAMP - INTERVAL '6 day' ) :: DATE,CURRENT_TIMESTAMP :: DATE, '1 days' ) AS T ;

當然6 day、1 day這些也是可修改的;

--統計最近30、7、昨天、今天的資料
SELECT
	count(*) AS AllData,
	count(*) filter ( WHERE create_time BETWEEN ( SELECT CURRENT_DATE - INTERVAL '30 day' ) AND CURRENT_DATE ) AS Last30DayData,
	count(*) filter ( WHERE create_time BETWEEN ( SELECT CURRENT_DATE - INTERVAL '7 day' ) AND CURRENT_DATE ) AS Last7DayData,
	count(*) filter ( WHERE create_time BETWEEN ( SELECT CURRENT_DATE - INTERVAL '1 day' ) AND CURRENT_DATE ) AS YesterdayData,
	count(*) filter ( WHERE create_time >= CURRENT_DATE ) AS todayAddData 
FROM
	table_name;

範例如下:查詢lic_plate欄位不為空和為空的最近7天的資料

-- 查詢lic_plate欄位不為空的最近7天的資料
select count(tn.lic_plate) AS number,tn.create_time AS percentage
from table_name tn
where tn.create_time in (SELECT DATE(T) AS DAY
                      FROM generate_series((CURRENT_TIMESTAMP - INTERVAL '6 day') :: DATE, CURRENT_TIMESTAMP :: DATE,'1 days') AS T) AND lic_plate is not null
group by tn.create_time order by tn.create_time;
 
-- 查詢lic_plate欄位為空的最近7天的資料
select count(id)  AS number,CSQV.create_time AS percentage
from  (select * from table_name tn where lic_plate is  null) AS CSQV where CSQV.create_time in (SELECT DATE(T) AS DAY
                      FROM generate_series((CURRENT_TIMESTAMP - INTERVAL '6 day') :: DATE, CURRENT_TIMESTAMP :: DATE,'1 days') AS T)
group by CSQV.create_time;

2、用SQL語句實現替換欄位裡的內容

思路:使用替換函數替換即可

-- 替換語句
update 表名 set 替換欄位名 = replace(替換欄位名,'被替換內容','替換內容');

範例如下:將 my_test 表的 test_content 欄位內容進行替換

update my_test set test_content = replace(test_content,'1','18');

替換函數:如果沒有可以建立,建立函數如下:

-- replace all occurrences in string of old_substr with new_substr 
-- auto-generated definition
create function replace(text, text, text) returns text
    immutable
    strict
    cost 1
    language internal
as
$$begin
-- missing source code
end;$$;
 
 
comment on function replace(text, text, text) is 'replace all occurrences in string of old_substr with new_substr';

3、SQL將查詢結果賦值

--查詢表資料,給test_content欄位並賦值
select test_id,test_code,'測試資料' test_content from my_test;
--查詢表資料給自定義 ABCD欄位 並賦值
select test_id,test_code,'測試資料' ABCD from my_test;

4、SQL查詢欄位內容為 NULL值時候賦值

select test_id,test_code,COALESCE(test_content,'測試資料') ABCD from my_test;
-- ||
select test_id,test_code,
       CASE
           WHEN test_content IS NOT NULL THEN test_content
           ELSE '測試資料'
           END ABCD from my_test;

總結

到此這篇關於PGSQL查詢最近N天的資料及SQL語句實現替換欄位內容的文章就介紹到這了,更多相關PGSQL查詢最近N天資料內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com