Mahesh
Mahesh

Reputation: 129

how to retrieve data from database monthly based on date if data not available it should display null

I have data like this format...

ID  id  date                     time           total
-----------------------------------------------------------    
51  192 2012-08-14 00:00:00.000 02:10 PM    4900.00
51  191 2012-08-11 00:00:00.000 03:20 PM    5500.00
51  35  2012-08-17 00:00:00.000 10:30 AM    2900.00
51  35  2012-08-17 00:00:00.000 11:50 AM    10800.00
51  192 2012-10-23 00:00:00.000 04:00 PM    2900.00
51  192 2012-10-23 00:00:00.000 03:00 PM    2900.00
51  192 2012-10-23 00:00:00.000 10:10 AM    2900.00
51  192 2012-10-23 00:00:00.000 02:50 PM    2300.00
51  191 2012-11-16 00:00:00.000 04:00 PM    2900.00

I would like to display sum(total) on a monthly basis. If bookings are not available entire month that month should display 0 value. Because I would like to plot that month value to chart.

Could you please help on this query?

Upvotes: 1

Views: 2019

Answers (3)

Joe G Joseph
Joe G Joseph

Reputation: 24106

try this:

select  Years,number as Month,isnull(Total,0) as Total
from(
    select number 
    from master..spt_values 
    where type='P' 
    and number between 1 and 12) seq
cross join (select distinct Year([date]) as Years from Table1) y
left join
    (select Year([date])as Year,month([date])as Month,sum(total) as Total
     from Table1 
     group by  Year([date]),month([date]))t
on seq.number=t.Month
and t.year=y.Years            


SQL fiddle demo

Upvotes: 1

Justin
Justin

Reputation: 9724

Query :

SQLFIDDLEExample

SELECT 
t.month
,isnull(SUM(total),0) AS total
FROM (VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12)
      )  AS t(month)
LEFT JOIN Table1 t1
  ON MONTH(t1.date) = t.month
GROUP BY t.month

Result:

| MONTH | TOTAL |
-----------------
|     1 |     0 |
|     2 |     0 |
|     3 |     0 |
|     4 |     0 |
|     5 |     0 |
|     6 |     0 |
|     7 |     0 |
|     8 | 24100 |
|     9 |     0 |
|    10 | 11000 |
|    11 |  2900 |
|    12 |     0 |

Upvotes: 0

GKV
GKV

Reputation: 501

this one works in oracle

  select  <place your rest  of required columns> 
    ,to_char(date,'month') Month,sum(total) total 
     from talbe1 group by to_char(date,'month')
      ,<place your rest  of required columns> ;

Upvotes: 0

Related Questions