Нормализација и подобрувања на дизајнот: SQL_queries.sql

File SQL_queries.sql, 2.0 KB (added by 183284, 33 hours ago)
Line 
1--Најново членство по член
2SELECT c.clenid, c.ime, c.prezime, p.ime AS paket, m.start_datum
3FROM clenovi c
4JOIN LATERAL (
5 SELECT m.*
6 FROM clenstvo m
7 WHERE m.clenid = c.clenid
8 ORDER BY m.start_datum DESC
9 LIMIT 1
10) m ON true
11JOIN paketi p ON p.paketid = m.paketid
12WHERE m.start_datum <= current_date;
13--Активни членства на даден ден со времетраење
14
15--Топ пакети по број на активни членства денес
16WITH period AS (
17 SELECT m.clenid, m.paketid, m.start_datum,
18 (m.start_datum + (tv.vremetraenjedenovi || ' days')::interval)::date AS end_datum
19 FROM clenstvo m
20 JOIN tip_vremetranje tv ON tv.vremetraenjeid = m.vremetraenjeid
21)
22SELECT c.clenid, c.ime, c.prezime, p.ime AS paket, period.start_datum, period.end_datum
23FROM period
24JOIN clenovi c ON c.clenid = period.clenid
25JOIN paketi p ON p.paketid = period.paketid
26WHERE period.start_datum <= current_date
27 AND current_date < period.end_datum;
28
29
30 WITH active AS (
31 SELECT m.paketid
32 FROM clenstvo m
33 JOIN tip_vremetranje tv ON tv.vremetraenjeid = m.vremetraenjeid
34 WHERE m.start_datum <= current_date
35 AND current_date < (m.start_datum + (tv.vremetraenjedenovi || ' days')::interval)::date
36)
37SELECT p.ime AS paket, COUNT(*) AS broj_aktivni
38FROM active a
39JOIN paketi p ON p.paketid = a.paketid
40GROUP BY p.ime
41ORDER BY broj_aktivni DESC;
42
43--Членови без посета во последни 30 дена
44SELECT c.clenid, c.ime, c.prezime
45FROM clenovi c
46LEFT JOIN LATERAL (
47 SELECT 1
48 FROM poseti po
49 WHERE po.clenid = c.clenid
50 AND po.datum >= current_date - INTERVAL '30 days'
51 LIMIT 1
52) x ON true
53WHERE x IS NULL;
54--Последна посета по локација и член
55SELECT c.clenid, c.ime, l.ime AS lokacija, max(po.datum) AS last_visit
56FROM poseti po
57JOIN clenovi c ON c.clenid = po.clenid
58JOIN lokacii l ON l.lokacijaid = po.lokacijaid
59GROUP BY c.clenid, c.ime, l.ime
60ORDER BY last_visit DESC;