-
Notifications
You must be signed in to change notification settings - Fork 0
/
SOLUTION (Hinzhul).sql
63 lines (58 loc) · 1.55 KB
/
SOLUTION (Hinzhul).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
WITH ActualPhones AS
-- Âèá³ð îäíîãî àêòóàëüíîãî íîìåðó òåëåôîíó äëÿ êîæíîãî àáîíåíòà
(
SELECT ContractID, MIN(Phone) AS Phone
FROM Phones WHERE Status = 'actual'
GROUP BY ContractID
),
InqCount AS
-- ʳëüê³ñòü çâåðíåíü çà îñòàíí³ 30 äí³â äëÿ êîæíîãî àáîíåíòà
(
SELECT ContractID, COUNT(InquiryID) AS InqCount
FROM Enquiries
WHERE DATEDIFF(day, RegDate, GETDATE()) between 0 and 30
GROUP BY ContractID
),
InqPeriod AS
-- Ïðîì³æîê ÷àñó ì³æ ïåðøèì òà îñòàíí³ì çâåðíåííÿì çà îñòàíí³ 30 äí³â
(
SELECT ContractID,
DATEDIFF(day, MIN(RegDate), MAX(RegDate)) AS InqDatesDiff
FROM Enquiries
WHERE DATEDIFF(day, RegDate, GETDATE()) between 0 and 30
GROUP BY ContractID
),
InqRecent AS
-- Äàòà òà òèï îñòàííüîãî çâåðíåííÿ
(
SELECT ContractID, RegDate AS RecentInqDate, InqTypeName AS RecentInqType
FROM Enquiries
WHERE RegDate =
(
SELECT MAX(RegDate)
FROM Enquiries AS enq
WHERE Enquiries.ContractID = enq.ContractID
GROUP BY ContractID
)
),
RevSum AS
-- Ñóìàðí³ íàðàõóâàííÿ çà äîãîâîðîì çà îñòàíí³ 30 äí³â
(
SELECT ContractID, SUM(Rev) AS InqRevSum
FROM Revenue
WHERE DATEDIFF(day, CONVERT(date, Period), GETDATE()) between 0 and 30
GROUP BY ContractID
)
-- ÐÅÇÓËÜÒÀÒ
SELECT ActualPhones.ContractID,
InqCount,
RecentInqDate,
RecentInqType,
InqDatesDiff,
Phone,
InqRevSum
FROM ActualPhones
JOIN InqCount ON ActualPhones.ContractID = InqCount.ContractID
JOIN InqPeriod ON InqPeriod.ContractID = InqCount.ContractID
JOIN InqRecent ON InqPeriod.ContractID = InqRecent.ContractID
JOIN RevSum ON InqRecent.ContractID = RevSum.ContractID;