I’m working on pulling a report and my numbers aren’t adding up. I am trying to pull the number of (unique) clients in 6 different age groups that had non-voided vouchers in a date range.
Here’s what I’ve got so far:
SELECT COUNT(DISTINCT V.clientId)
FROM ClientManagement_Client_Vouchers V
INNER JOIN ClientManagement_Client_Voucher_Items VI
ON V.id = VI.voucherId
INNER JOIN ClientManagement_Clients C
ON V.clientId = C.id
WHERE V.dateVoided IS NULL
AND V.dateCreated >= '2011-01-01'
AND V.dateCreated <= '2011-06-30'
GROUP BY
DATE_FORMAT(V.dateCreated, '%Y') - DATE_FORMAT(C.dob, '%Y') - (DATE_FORMAT(V.dateCreated, '00-%m-%d') < DATE_FORMAT(C.dob, '00-%m-%d')) < 5,
( DATE_FORMAT(V.dateCreated, '%Y') - DATE_FORMAT(C.dob, '%Y') - (DATE_FORMAT(V.dateCreated, '00-%m-%d') < DATE_FORMAT(C.dob, '00-%m-%d')) >= 5 AND
DATE_FORMAT(V.dateCreated, '%Y') - DATE_FORMAT(C.dob, '%Y') - (DATE_FORMAT(V.dateCreated, '00-%m-%d') < DATE_FORMAT(C.dob, '00-%m-%d')) <= 9
),
(
DATE_FORMAT(V.dateCreated, '%Y') - DATE_FORMAT(C.dob, '%Y') - (DATE_FORMAT(V.dateCreated, '00-%m-%d') < DATE_FORMAT(C.dob, '00-%m-%d')) >= 10 AND
DATE_FORMAT(V.dateCreated, '%Y') - DATE_FORMAT(C.dob, '%Y') - (DATE_FORMAT(V.dateCreated, '00-%m-%d') < DATE_FORMAT(C.dob, '00-%m-%d')) <= 18
),
(
DATE_FORMAT(V.dateCreated, '%Y') - DATE_FORMAT(C.dob, '%Y') - (DATE_FORMAT(V.dateCreated, '00-%m-%d') < DATE_FORMAT(C.dob, '00-%m-%d')) >= 19 AND
DATE_FORMAT(V.dateCreated, '%Y') - DATE_FORMAT(C.dob, '%Y') - (DATE_FORMAT(V.dateCreated, '00-%m-%d') < DATE_FORMAT(C.dob, '00-%m-%d')) <= 59
),
(
DATE_FORMAT(V.dateCreated, '%Y') - DATE_FORMAT(C.dob, '%Y') - (DATE_FORMAT(V.dateCreated, '00-%m-%d') < DATE_FORMAT(C.dob, '00-%m-%d')) >= 60 AND
DATE_FORMAT(V.dateCreated, '%Y') - DATE_FORMAT(C.dob, '%Y') - (DATE_FORMAT(V.dateCreated, '00-%m-%d') < DATE_FORMAT(C.dob, '00-%m-%d')) <= 64
),
DATE_FORMAT(V.dateCreated, '%Y') - DATE_FORMAT(C.dob, '%Y') - (DATE_FORMAT(V.dateCreated, '00-%m-%d') < DATE_FORMAT(C.dob, '00-%m-%d')) >= 65
WITH ROLLUP
This gives the following rows:
186
186
161
161
343
1547
1547
1547
1887
186
186
186
186
2072
108
108
108
108
108
2180
73
73
73
73
73
73
2252
The bottom number is correct (2252 total unique clients for the criteria) - but none of the other numbers add up: for example, 186 + 161 = 347, not the 343 that the rollup is showing.
taking the ‘with rollup’ clause out, i’m left with simply:
186
161
1547
186
108
73
which adds up to 2261, not the correct number 2252.
Where am I going wrong?