-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.sql
71 lines (71 loc) · 1.44 KB
/
main.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
WITH maintable AS (
SELECT
e.contractid,
p.phone AS primaryphone,
COUNT(e.inquiryid) AS totalqueries,
MAX(e.regdate) AS lastregistrationdate
FROM
enquiries e
JOIN phones p ON e.contractid = p.contractid
AND e.regdate >= DATEADD(DAY, -30, GETDATE())
AND p.status <> 'notactual'
GROUP BY
e.contractid,
p.phone,
p.status
),
lasttypename AS (
SELECT
inqtypename AS lastquerytype,
contractid
FROM
enquiries
WHERE
regdate IN (
SELECT
MAX(regdate) AS lastregistrationdate
FROM
enquiries
GROUP BY
contractid
)
),
diffdate AS (
SELECT
e.contractid,
DATEDIFF(DAY, MAX(e.regdate) - MIN(e.regdate)) AS diffdate
FROM
enquiries e
JOIN phones p ON e.contractid = p.contractid
AND e.regdate >= CURRENT_DATE - INTERVAL '30 days'
AND p.status <> 'notactual'
GROUP BY
e.contractid
),
totalrev AS (
SELECT
contractid,
SUM(rev) AS totalrevenue
FROM
revenue
WHERE
CONVERT(DATE, CAST(period AS INT), 112) >= DATEADD(DAY, -30, GETDATE())
GROUP BY
contractid
)
UPDATE
uniquesubscribers us
SET
totalqueries = m.totalqueries,
primaryphone = m.primaryphone,
lastregistrationdate = m.lastregistrationdate,
lastquerytype = lt.lastquerytype,
diffdate = df.diffdate,
totalrevenue = tr.totalrevenue
FROM
maintable m
JOIN lasttypename lt ON m.contractid = lt.contractid
JOIN diffdate df ON m.contractid = df.contractid
LEFT JOIN totalrev tr ON m.contractid = tr.contractid
WHERE
us.contractid = m.contractid