I need to product a report from the data set below. The report is supposed to show, for each day, the sum of columns P, U, D, F and M, as well as a ratio: M / P+U in aggregate form.
I’m having trouble with the ratio. I’m not sure how to cater for the division by zero.
TYP | TIMESTAMP | P | U | D | F | M
------------------------------------------------------------
L | 2012-04-27 15:47:02.000 | 0 | 949 | 0 | 0 | 949
L | 2012-04-27 15:48:18.000 | 0 | 949 | 0 | 0 | 949
L | 2012-04-30 17:15:01.000 | 0 | 0 | 4051| 0 | 0
L | 2012-04-30 17:44:44.000 | 0 | 984 | 5 | 0 | 986
L | 2012-05-02 11:12:01.000 | 2117| 0 | 0 | 0 | 0
L | 2012-05-02 11:12:09.000 | 149 | 4 | 210 | 0 | 157
L | 2012-05-02 11:12:11.000 | 77 | 0 | 30 | 0 | 43
My query:
SELECT
CONVERT(date,TIMESTAMP,112) As 'DAY',
SUM(P) As PAS,
SUM(U) As UFR,
SUM(D) As DES,
SUM(F) As FIR,
SUM(M) As MOL,
[M%] = ISNULL( (SUM(M) / NULLIF( SUM(P)+SUM(U), 0 ) )*100, 0),
FROM DATASET
GROUP BY CONVERT(date,TIMESTAMP,112) ORDER BY CONVERT(date,TIMESTAMP,112) DESC
UPDATE: this is the report
DAY | PAS | UFR | DES | FIR | MOL | M%
----------------------------------------------------------------
2012-05-02 | 2343 | 4 | 240 | 0 | 200 | 0
2012-04-30 | 0 | 984 | 4056 | 0 | 986 | 100
2012-04-27 | 0 | 1898 | 0 | 0 | 1898 | 100
The problem is that you are not accounting for integer division.
SQL Fiddle version