1

我有这种格式的数据...

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

我想sum(total)按月显示。如果整个月都没有预订,则该月应显示 0 值。因为我想将该月的值绘制到图表中。

你能帮忙解决这个问题吗?

4

3 回答 3

1

试试这个:

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小提琴演示

于 2012-11-21T07:06:55.183 回答
0

这个在甲骨文中工作

  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> ;
于 2012-11-21T06:55:58.523 回答
0

询问 :

SQLFIDDLE示例

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

结果:

| 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 |
于 2012-11-21T07:18:41.817 回答