groditi is now going to shout at me for making syntax up in 3, 2, 1 ...
[dbsrgits/SQL-Abstract.git] / etc / having-cases.sql
CommitLineData
6eaca423 1
2-- CASE 1
3SELECT users.name, SUM(commission) AS total
4 FROM commissions
5 INNER JOIN users ON ( commissions.recipient_id = users.id )
6 WHERE commissions.entry_date > '2007-01-01'
7 GROUP BY commissions.recipient_id
8 HAVING total > 500
9 ORDER BY total DESC;
10
a2ce21a0 11order_by { $_->total }
12 select { $_->users->name, [ total => sum($_->aggregates->commission) ] }
13 where { sum($_->aggregates->commission) > 500 }
14group_by { $_->commissions->recipient_id }
15 join { $_->users->id == $_->commissions->recipient_id }
16 [ users => expr { $_->users } ],
17 [ commission => expr { $_->commissions } ];
18
19my $total = [ -sum => [ -name => 'commission' ] ];
20
21[
22 -select,
23 [
24 -list,
25 [ -name => qw(users name) ],
26 $total
27 [
28 -where,
29 [ '>', $total, [ -value, 500 ] ],
30 [
31 -group_by,
32 [ -name, qw(commissions recipient_id) ],
33 [
34 -where,
35 [ '>', [ -name, qw(commissions entry_date) ], [ -value, '2007-01-01' ] ],
36 [
37 -join,
38 ...
39 ],
40 ],
41 ],
42 ],
43]
44
6eaca423 45-- CASE 2
46SELECT users.name, aggregates.total FROM (
47 SELECT recipient_id, SUM(commission) AS total
48 FROM commissions
49 WHERE commissions.entry_date > '2007-01-01'
50 GROUP BY commissions.recipient_id
51 HAVING total > 500
52 ) AS aggregates
53INNER JOIN users ON(aggregates.recipient_id = users.id)
54ORDER BY aggregates.total DESC;
55
a2ce21a0 56order_by { $_->aggregates->total }
57 select { $_->users->name, $_->aggregates->total }
58 join { $_->users->id == $_->aggregates->recipient_id }
59 [ users => expr { $_->users } ],
60 [ aggregates =>
61 expr {
62 select { $_->recipient_id, [ total => sum($_->commission) ] }
63 where { sum($_->commission) > 500 }
64 group_by { $_->recipient_id }
65 where { $_->entry_date > '2007-01-01' }
66 expr { $_->commissions }
67 }
68 ];
69
70
6eaca423 71-- CASE 3
72SELECT users.name, aggregates.total FROM (
73 SELECT recipient_id, SUM(commission) AS total
74 FROM commissions
75 WHERE commissions.entry_date > '2007-01-01'
76 GROUP BY commissions.recipient_id
77 ) AS aggregates
78INNER JOIN users ON(aggregates.recipient_id = users.id)
79WHERE aggregates.total > 500
80ORDER BY aggregates.total DESC
a2ce21a0 81
82
83order_by { $_->aggregates->total }
84 select { $_->users->name, $_->aggregates->total }
85 where { $_->aggregates->total > 500 }
86 join { $_->users->id == $_->aggregates->recipient_id }
87 [ users => expr { $_->users } ],
88 [ aggregates =>
89 expr {
90 select { $_->recipient_id, [ total => sum($_->commission) ] }
91 group_by { $_->recipient_id }
92 where { $_->entry_date > '2007-01-01' }
93 expr { $_->commissions }
94 }
95 ];