John Smith
John Smith

Reputation: 808

SQL / Coalesce - Wrong row name

I have a problem with the request below!

REQUEST:

SELECT COALESCE(date(date_field), 'Total') AS "date_field_group",
COUNT( id_field ) AS  "Nombre de bookings",
CONCAT( REPLACE( REPLACE( FORMAT( SUM( price1 ) , 2 ) , ',',  ' ' ) ,  '.',  ',' ) ,  ' €' ) AS  "Total à l'achat",
CONCAT( REPLACE( REPLACE( FORMAT( SUM( price2 ) , 2 ) ,  ',',  ' ' ) ,  '.',  ',' ) ,  ' €' ) AS  "Total à la vente",
CONCAT( REPLACE( REPLACE( FORMAT( SUM( price2 ) - SUM( price1 ) , 2 ) ,  ',',  ' ' ) ,  '.',  ',' ) ,  ' €' ) AS  'Marge',
CONCAT( REPLACE( FORMAT( (SUM( price2 ) / SUM( price1 ) ) , 2 ) ,  '1.',  '' ) ,  ' ',  '%') AS  "Markup moyen"
FROM table1 S, table2 B
WHERE status_field
IN ( "1",  "5")
AND DATE( date_field ) BETWEEN  "2011-08-01" AND  "2011-08-31"
AND type_field =  "H"
AND price1 IS NOT NULL 
AND S.id_field = B.id_field
AND B.id2 =  "1"
GROUP BY date_field_group WITH ROLLUP

The thing is that the request is working fine (right numbers), but in the last line I was expected to get in first row "Total" and instead of that I got a field NULL...

Is someone know what is wrong with my request ? Thx for any help ;).

Upvotes: 1

Views: 235

Answers (1)

Johan
Johan

Reputation: 76753

You're query is almost correct (except for using implicit SQL '89 joins, which is an SQL anti-pattern)

The problem is in the last line: GROUP BY ... WITH ROLLUP.
The rollup gets applied very late in the process, after your COALESCE(date(date_field), 'Total').
So the coalesce has already finished by the time rollup comes along you need to rewrite the query like so:

SELECT COALESCE(date_field_group, 'Total') as date_field_group
  , `Nombre de bookings`
  , `Total à l'achat`
  , `Total à la vente`
  , `Marge`
  , `Markup moyen`
FROM (
   SELECT date(date_field) AS "date_field_group",   
     COUNT( id_field ) AS  "Nombre de bookings",   
     CONCAT( REPLACE( REPLACE( FORMAT( SUM( price1 ) , 2 ) , ',',  ' ' ) ,  '.',  ',' ) ,  ' €' ) AS  "Total à l'achat",   
     CONCAT( REPLACE( REPLACE( FORMAT( SUM( price2 ) , 2 ) ,  ',',  ' ' ) ,  '.',  ',' ) ,  ' €' ) AS  "Total à la vente",   
    CONCAT( REPLACE( REPLACE( FORMAT( SUM( price2 ) - SUM( price1 ) , 2 ) ,  ',',  ' ' ) ,  '.',  ',' ) ,  ' €' ) AS  'Marge',   
    CONCAT( REPLACE( FORMAT( (SUM( price2 ) / SUM( price1 ) ) , 2 ) ,  '1.',  '' ) ,  ' ',  '%') AS  "Markup moyen"   
  FROM table1 S
  INNER JOIN table2 B ON (S.id_field = B.id_field)   
  WHERE status_field IN ( "1",  "5")   
    AND DATE( date_field ) BETWEEN  "2011-08-01" AND  "2011-08-31"   
    AND type_field =  "H"   
    AND price1 IS NOT NULL    
    AND B.id2 =  "1"   
  GROUP BY date_field_group WITH ROLLUP ) AS subquery

Upvotes: 1

Related Questions