![]() | |
#1
| |||
| |||
|
#2
| |||
| |||
|
|
Hello all. I need help using query here. I'm using this query and make grouping by date(month) with this query SELECT p.name,MONTHNAME(s.date) as month,sum(CASE WHEN d.quantity is NULL THEN 0 ELSE d.quantity END ) AS sumTotal from products p left outer join (sales s right outer join sales_details d on s.id=d.sale_id) on p.id=d.product_id WHERE S.date BETWEEN CAST('2007-01-01 00:00:00' as Datetime) AND CAST('2007-07-30 23:59:59' as Date) group by p.id,MONTHNAME(s.date); In this query, it not shows the product that doesn't have record in the date range on sales_detail and one more thing, it is also doesn't show the month where there is no record in sales on the date range. For example if my products table have 5 records then with month 1-7 the query will give 35 records (5*7), where in some record the value of sumTotal is 0, because on that month the product never sale. Does someone have idea or suggestion or hint? Thank you. |
#3
| |||
| |||
|
#4
| |||
| |||
|
|
Hi Lennart. Thanks for your reply. I have tried your suggestion, here my new query (I'm using mysql 5) SELECT p.name,MONTHNAME(s.date) as month,sum(CASE WHEN d.quantity is NULL THEN 0 ELSE d.quantity END ) AS sumTotal from products p left outer join (sales s inner join sales_details d on s.id=d.sale_id) on p.id=d.product_id WHERE S.date BETWEEN CAST('2007-01-01 00:00:00' as Datetime) AND CAST('2007-07-30 23:59:59' as Date) group by p.id,month Union SELECT p.name, MONTHNAME( s.date ) AS MONTH , 0 AS sumTotal FROM products p, sales s WHERE NOT EXISTS (SELECT p.name, MONTHNAME( s.date ) AS MONTH , sum(CASE WHEN d.quantity IS NULL THEN 0 ELSE d.quantity END ) AS sumTotal FROM products p LEFT OUTER JOIN ( sales s INNER JOIN sales_details d ON s.id = d.sale_id ) ON p.id = d.product_id WHERE S.date BETWEEN CAST( '2007-01-01 00:00:00' AS Datetime ) AND CAST( '2007-07-30 23:59:59' AS Date ) GROUP BY p.id, MONTH ); It still doesn't give me the 0 value for my question. Where did i make mistake for my new query, because i understand that WHERE NOT EXISTS will give me value 0 for condition where it give nothing. |
#5
| |||
| |||
|
![]() |
| Thread Tools | |
| Display Modes | |
| |