我有像这种格式的数据......
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值。因为我想将月份值绘制成图表。
你能帮忙解决一下这个问题吗?
答案 0 :(得分: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
答案 1 :(得分:0)
这个在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> ;
答案 2 :(得分:0)
查询:
<强> 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
结果:
| 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 |