从表中生成随机值

时间:2017-03-07 23:24:06

标签: postgresql

我想生成随机值以填充表格。

首先,我有一个city_table:

CREATE TABLE t_city_ci (
   ci_id SERIAL PRIMARY KEY,
   ci_name VARCHAR(100) NOT NULL
);

所以我插入这样的随机值:

INSERT INTO t_city_ci ("ci_name")
SELECT DISTINCT(d.str)
FROM (
SELECT
    (
            SELECT string_agg(x, '') as str
            FROM (
                    SELECT chr(ascii('A') + (random() * 25)::integer)
                    -- reference 'b' so it is correlated and re-evaluated
                    FROM generate_series(1, 10 + b * 0)
            ) AS y(x)
    )
    FROM generate_series(1,10000) as a(b)) as d;

现在,我有一个如下所示的温度表:

CREATE TABLE dw_core.t_temperatures_te (
   te_id SERIAL PRIMARY KEY,
   ci_id INTEGER,
   te_temperature FLOAT NOT NULL,
   te_date TIMESTAMP NOT NULL DEFAULT NOW()
);

如何填写温度表:

  • 去年的随机日期
  • 随机温度介于-30和50之间
  • 来自t_city表的随机值?

我试过了,但日期永远不会改变:

INSERT INTO dw_core.t_temperatures_te ("ci_id","te_temperature","te_date")
 SELECT  *
            FROM (
                    SELECT (random() * (SELECT MAX(ci_id) FROM dw_core.t_city_ci) + 1)::integer
                    -- reference 'b' so it is correlated and re-evaluated
                    FROM generate_series(1, 100000 )
            ) AS y
          ,(select random() * -60 + 45 FROM generate_series(1,1005)) d(f),
          (select timestamp '2014-01-10 20:00:00' +
   random() * (timestamp '2014-01-20 20:00:00' -
               timestamp '2016-01-10 10:00:00')) dza(b)
               LIMIT 1000000;

非常感谢

1 个答案:

答案 0 :(得分:0)

这样的东西?

select * from (
    select
        (random() * 100000)::integer as ci_id,
        -30 + (random() * 80) as temp,
        '2014-01-01'::date + (random() * 365 * '1 day'::interval) as time_2014
    from generate_series(1,1000000) s
) foo
inner join t_city_ci c on c.ci_id = foo.ci_id;

以下是生成数据的示例:

select
     (random() * 100000)::integer as ci_id,
     -30 + (random() * 80) as temp,
     '2014-01-01'::date + (random() * 365 * '1 day'::interval) as time_2014
from generate_series(1,10);
 ci_id |       temp        |         time_2014
-------+-------------------+----------------------------
 84742 |  31.6278865475337 | 2014-10-16 21:36:45.371176
 16390 |   10.665458049935 | 2014-11-13 19:59:54.148177
 87067 |  43.2082599369847 | 2014-06-01 16:14:43.021094
 25718 | -7.78245567240867 | 2014-07-23 05:53:10.036914
 99538 | -5.82924078024423 | 2014-06-08 06:44:02.081918
 71720 |  22.3102275898262 | 2014-06-15 08:24:00.327841
 24740 |  4.65809369210996 | 2014-05-19 02:20:58.804213
 56861 |  -20.750980894431 | 2014-10-01 06:09:54.117367
 47929 | -24.4018202994027 | 2014-11-24 13:39:54.096337
 30772 |  46.7239395141247 | 2014-08-27 04:50:46.785239
(10 rows)