-
Notifications
You must be signed in to change notification settings - Fork 0
/
sql_HAVING.sql
83 lines (73 loc) · 2.02 KB
/
sql_HAVING.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
72
73
74
75
76
77
78
79
80
81
82
"How many accounts have more than 20 orders?"
SELECT a.id, a.name, COUNT(*) num
FROM account a
JOIN orders o
ON a.id = o.account_id
GROUP BY a.id, a.name
HAVING COUNT(*) > 20
ORDER BY num;
"Which account has the most orders?"
SELECT a.id, a.name, COUNT(*) num
FROM accounts a
JOIN orders o
ON a.id = o.account_id
GROUP BY a.id, a.name
ORDER BY num DESC
LIMIT 1;
"How many accounts spent more than 30,000 usd total across all orders?"
SELECT a.id, a.name, SUM(o.total_amt_usd) total
FROM accounts a
JOIN orders o
ON a.id = o.account_id
GROUP BY a.id, a.name
HAVING SUM(o.total_amt_usd) > 30000
ORDER BY total;
"How many accounts spent less than 1,000 usd total across all orders?"
SELECT a.id, a.name, SUM(o.total_amt_usd) total
FROM accounts a
JOIN orders o
ON a.id = o.account_id
GROUP BY a.id, a.name
HAVING SUM(o.total_amt_usd) < 1000
ORDER BY total;
"Which account has spent the most with us?"
SELECT a.id, a.name, SUM(o.total_amt_usd) total
FROM accounts a
JOIN orders o
ON a.id = o.account_id
GROUP BY a.id, a.name
ORDER BY total DESC
LIMIT 1;
"Which account has spent the least with us?"
SELECT a.id, a.name, SUM(o.total_amt_usd) total
FROM accounts a
JOIN orders o
ON a.id = o.account_id
GROUP BY a.id, a.name
ORDER BY total
LIMIT 1;
"Which accounts used facebook as a channel to contact customers more than 6 times?"
SELECT a.id, a.name, w.channel, COUNT(*) count_time
FROM accounts a
JOIN web_events w
ON a.id = w.account_id
GROUP BY a.id, a.name, w.channel
HAVING COUNT(*) > 6 and w.channel = 'facebook'
ORDER BY count_time;
"Which account used facebook most as a channel?"
SELECT a.id, a.name, w.channel, COUNT(*) count_time
FROM accounts a
JOIN web_events w
ON a.id = w.account_id
WHERE w.channel = 'facebook'
GROUP BY a.id, a.name, w.channel
ORDER BY count_time DESC
LIMIT 1;
"Which channel was most frequently used by most accounts?"
SELECT a.id, a.name, w.channel, COUNT(*) count_time
FROM accounts a
JOIN web_events w
ON a.id = w.account_id
GROUP BY a.id, a.name, w.channel
ORDER BY count_time DESC
LIMIT 10;