针对 Postgres生成数据方法
<1>生成序列 SELECT * FROM generate_series(1,5);
<2>生成date SELECT date(generate_series(now(), now() + '1 week', '1 day'));
<3>生成integer 随机数 SELECT (random()*(2*10^9))::integer;
<4>生成numeric 随机数 select (random()*100)::numeric(4,2);
<5>生成字符串 select substr('abcdefghijklmnopqrstuvwxyz',1,(random()*26)::integer);
<6>生成重复串 select repeat('1',(random()*40)::integer);
案例
test=# SELECT generate_series(1,10) as key,(random()*100.)::numeric(4,2),repeat('1',(random()*25)::integer) ORDER BY random();
key | numeric | repeat
-----+---------+-------------------------
1 | 75.44 | 11111111111111111111111
6 | 13.91 | 111111
3 | 67.40 | 1111111111111111111111
9 | 65.63 | 1111111111111
10 | 20.38 | 111111
4 | 45.07 | 111111111111111111111
2 | 35.92 | 111
8 | 46.18 | 11111111111111
5 | 20.97 | 11111111111111
7 | 55.41 |
(10 rows)
select i from (select t as i from generate_series(1,11) t) a where a.i in(1,2,3,4,11) order by a.i asc
根据连续数据 取需要指定的数据
二、
如果您想知道执行该sql的时间,请在执行上述命令前设置:
postgres=# \timing on
Timing is on.
(1)测试参考SQL,可以把生成的随机值改的大一些;
#生成新表===>
select i,'text:'||i as text into test from generate_series(1,10) as i;
#在新表中插入测试数据===>
insert into test(i,text) select i,'text:'||i from generate_series(1,10) as i;
--不管什么时候执行都能取完整的一天
select now()::date-interval'0 day',now()::date + interval '86399 s';
--今天
select now()::date + interval'0 s' , now()::date + interval '86399 s'
--昨天
select (now()::date - interval'1 day')+interval '0 s' , (now()::date - interval'1 day')+ interval '86399 s';
--昨天
select now()::date - interval '86400 s',now()::date - interval '1 s';
SELECT date(generate_series(now()- interval '7 day', now(), '1 day'));
"2017-07-07"
"2017-07-08"
"2017-07-09"
"2017-07-10"
"2017-07-11"
"2017-07-12"
"2017-07-13"
"2017-07-14"
SELECT date(generate_series(now(), now() + '1 week', '1 day'));
"2017-07-14"
"2017-07-15"
"2017-07-16"
"2017-07-17"
"2017-07-18"
"2017-07-19"
"2017-07-20"
"2017-07-21"
简单案例
地区:华东 中南 东北 西南 华北 西北
时间 :现在-未来三年
状态:0 已收费 1 待收费 2 交易中
日交易额:总体上涨的趋势
drop table mock_transaction;
create table mock_transaction(
tran_id serial not null primary key,
district_name character varying(3),
create_time timestamp(0) with time zone,
tran_status smallint,
daily_turnover int
);
drop function mock_transaction();
create or replace function mock_transaction()
returns void as $$
declare
district character varying[];
begin
district := array['华东','中南','东北','西南','华北','西北'];
insert into mock_transaction(district_name,create_time,tran_status,daily_turnover)
select district[round(random()*5+1)] as district_name,
now()::date + (i||' day')::interval,
round(random()*3) as tran_status,
round(1000+i+random()*100) as daily_turnover
from generate_series(1,1000) as t(i);
--raise notice '%,%,%',rnd.ditrict_id,rnd.tran_status,rnd.daily_turnover;
end;
$$ language plpgsql;
select * from mock_transaction();