Инструменты пользователя

Инструменты сайта


it:postgresql:sql

Проверить наличие элемента массива

DECLARE
  lInt INTEGER;
  lArr INTEGER[];
BEGIN
  IF array[lInt] <@ lArr THEN
    ..
  END IF;
END

Заполнить таблицу миллионом строк

CREATE TABLE foo (c1 INTEGER, c2 text);
INSERT INTO foo
  SELECT i, md5(random()::text)
  FROM generate_series(1, 1000000) AS i;

Удалить дубликаты

DELETE FROM wgdump.dump WHERE ctid NOT IN (
	SELECT MAX(ctid) FROM wgdump.dump GROUP BY ts
); 

Пример рандома

--explain ANALYZE
WITH
temperature AS (
	SELECT ts + (INTERVAL '60 minutes' * random()) AS ts, city, (30*random())::INT AS temperature
	FROM generate_series('2022-01-01' :: TIMESTAMP,
	                     '2022-01-31', '1 day') AS ts,
	     unnest(array['Moscow', 'Berlin']) AS city
),
humidity AS (
	SELECT ts + (INTERVAL '60 minutes' * random()) AS ts, city, (100*random())::INT AS humidity
	FROM generate_series('2022-01-01' :: TIMESTAMP,
                     '2022-01-31', '1 day') AS ts,
     	unnest(array['Moscow', 'Berlin']) AS city
)
SELECT t.ts, t.city, t.temperature, h.humidity
FROM temperature AS t
LEFT JOIN LATERAL
  ( SELECT * FROM humidity
    WHERE city = t.city AND ts <= t.ts
    ORDER BY ts DESC LIMIT 1
  ) AS h ON TRUE
--WHERE t.ts < '2022-01-05'

Колво дней в месяце

SELECT

ts.day::date AS ts

,extract(day from date_trunc('month',ts.day) + interval '1 month -1 day') FROM generate_series('2023-01-01', '2023-12-01', interval '1 month') AS ts(day);

it/postgresql/sql.txt · Последнее изменение: 2023/04/16 11:20 — ura2404