我跟随表
CREATE TABLE public.af01
(
id integer NOT NULL DEFAULT nextval('af01_id_seq'::regclass),
idate timestamp without time zone,
region text,
city text,
vtype text,
vmake text,
vmodel text,
vregno text,
intime time without time zone,
otime time without time zone,
vstatus boolean,
remarks text,
vowner text
);
我需要在其中添加数据。此数据应为1年(从01-01-2016
到31-12-2016
的数据)。在一个日期中可以有5个条目,
Region
列必须包含3个值(Central,Western,Eastern
),
City
列必须包含3个值(City1
,City2
,City3
)
vtype
列是车辆类型,例如Heavy,light,Other
vmake
列是制造商Audi,Nissan,Toyota,Hyundai,GMC
等
vregno
此列适用于vechicle注册号,它应该是唯一的(Ex.reg no CFB 4587
)。
intime
任何一天中的随机时间('上午10:15和#39;)。
otime
此列应为intime
+ 5或10或15或20。vstatus
列应为True
或false
。
我最终使用此选择查询来生成日期行
select '2013-01-01'::date + (n || ' days')::interval days
from generate_series(0, 365) n;
和
生成Vehicle regno的第一部分。
SELECT substring(string_agg (substr('ABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil (random() * 62)::integer, 1), ''),1,3) t
FROM generate_series(0,45);
预期产出;
id idate region city vtype vmake vmodel vregno intime otime vstatus remarks vowner
-- ---------- ------- ----- -------------- ------ ------ -------- ------------------- ------------------- ------- ------- ------
1 2016-01-01 Central City1 Heavy Vechicle Nissan Model1 NGV 4578 12:15:00 12:30:00 1 NULL Tom
2 2016-01-01 Western City1 Light Audi S3 BFR 4587 10:20:00 10:40:00 1 NULL Jerry
答案 0 :(得分:2)
r_dates relation只是在范围内生成日期的简单方法。
other_const和max_const分别是数组及其长度。 region [(random()* region_max):: int2 + 1] - 通过随机选择数组中的元素
INSERT INTO af01 (idate, region, city, vtype, vmake, vregno, intime, otime, vstatus)
SELECT cd, r, c, v, vm, rn, intime, intime + len as otime, status
FROM (
WITH r_dates AS (
SELECT generate_series('2013-01-01'::date, '2013-12-31'::date, '1 day'::interval) as cd
), other_const AS (
SELECT '{Central,Western,Eastern}'::text[] AS region,
'{City1,City2,City3}'::text[] as cities,
'{Heavy,light,Other}'::text[] as vehicles,
'{Audi,Nissan,Toyota,Hyundai,GMC}'::text[] as vmakes,
'{5,10,15,20}'::int4[] AS lengths,
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'::text AS regnosrc
), max_const AS (
SELECT array_upper(region, 1) - 1 AS region_max,
array_upper(cities, 1) - 1 AS cities_max,
array_upper(vehicles, 1) - 1 AS vehicles_max,
array_upper(vmakes, 1) - 1 AS vmakes_max,
array_upper(lengths, 1) - 1 AS lengths_max
FROM other_const
)
SELECT cd,
region[(random() * region_max)::int2 + 1] AS r,
cities[(random() * cities_max)::int2 + 1] AS c,
vehicles[(random() * vehicles_max)::int2 + 1] AS v,
vmakes[(random() * vmakes_max)::int2 + 1] AS vm,
(
SELECT string_agg(s, '')
FROM (
SELECT substr(regnosrc, (random() * (length(regnosrc) - 1))::int4 + 1, 1) AS s
FROM generate_series(1, 3)
) AS a
)
|| lpad(((random() * 9999)::int8)::text, 4, '0') AS rn,
'00:00:00'::time + (((random() * 24 * 60)::int8)::text || 'min')::interval AS intime,
((lengths[(random() * lengths_max)::int2 + 1])::text || 'min')::interval AS len,
random() > 0.5 AS status
FROM r_dates, other_const, max_const, generate_series(1, 5)
) AS A