-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcount.sql
66 lines (66 loc) · 1.59 KB
/
count.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
WITH `users` AS (
SELECT DISTINCT `user`
FROM (
SELECT `user`
FROM `candidates`
LEFT JOIN `votes` ON `candidates`.`id` = `votes`.`candidate`
WHERE `candidates`.`election` = :id
UNION SELECT `user`
FROM `writeins`
WHERE `writeins`.`election` = :id
)
)
SELECT `c1`.`id` AS `c1`,
`c2`.`id` AS `c2`,
`c1`.`name` AS `n1`,
`c2`.`name` AS `n2`,
IFNULL(SUM(
`c1`.`rank` < `c2`.`rank`
OR `c1`.`rank` IS NOT NULL
AND `c2`.`rank` IS NULL
), 0) AS `a`,
IFNULL(SUM(
`c1`.`rank` > `c2`.`rank`
OR `c1`.`rank` IS NULL
AND `c2`.`rank` IS NOT NULL
), 0) AS `b`
FROM (
SELECT `candidates`.`id`,
`candidates`.`name`,
`users`.`user`,
`votes`.`rank`
FROM `candidates`
CROSS JOIN `users`
LEFT JOIN `votes` ON `users`.`user` = `votes`.`user`
AND `candidates`.`id` = `votes`.`candidate`
WHERE `candidates`.`election` = :id
UNION SELECT 0,
'',
`users`.`user`,
`writeins`.`rank`
FROM `users`
LEFT JOIN `writeins` ON `users`.`user` = `writeins`.`user`
) AS `c1`
INNER JOIN (
SELECT `candidates`.`id`,
`candidates`.`name`,
`users`.`user`,
`votes`.`rank`
FROM `candidates`
CROSS JOIN `users`
LEFT JOIN `votes` ON `users`.`user` = `votes`.`user`
AND `candidates`.`id` = `votes`.`candidate`
WHERE `candidates`.`election` = :id
UNION SELECT 0,
'',
`users`.`user`,
`writeins`.`rank`
FROM `users`
LEFT JOIN `writeins` ON `users`.`user` = `writeins`.`user`
) AS `c2` ON `c1`.`user` = `c2`.`user`
WHERE `c1`.`id` <> `c2`.`id`
GROUP BY `c1`.`id`,
`c2`.`id`
ORDER BY `a` > `b` DESC,
`a` DESC,
`b`