您好,登錄后才能下訂單哦!
這篇“PGSQL怎么查詢最近N天的數據及SQL語句實現替換字段內容的方法”文章的知識點大部分人都不太理解,所以小編給大家總結了以下內容,內容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“PGSQL怎么查詢最近N天的數據及SQL語句實現替換字段內容的方法”文章吧。
思路:先獲取當前的時間,然后更具當前時間去減去對應的天數,就可以得到需要的天數了。然后用這些天數作為條件,然后即可查詢出需要多少天的數據了。
-- 獲取當前時間 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;
思路:使用替換函數替換即可
-- 替換語句 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';
--查詢表數據,給test_content字段并賦值 select test_id,test_code,'測試數據' test_content from my_test; --查詢表數據給自定義 ABCD字段 并賦值 select test_id,test_code,'測試數據' ABCD from my_test;
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語句實現替換字段內容的方法”這篇文章的內容,相信大家都有了一定的了解,希望小編分享的內容對大家有幫助,若想了解更多相關的知識內容,請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。