用于计算的SQL查询按月计算

时间:2011-05-24 19:43:01

标签: sql sql-server

有什么方法可以在一个列中将1-12加入一列按月计算?...在​​SQL中

SELECT
    months???,
    count(whatever1) count1,
    count(whatever2) count2
FROM
    months????
    LEFT JOIN whatever1 ON
        month(whatever1.Date) = months???.monthid
    LEFT JOIN whatever2 ON
        month(whatever2.Date) = months???.monthid
GROUP BY
    months???
最终会像

那样的东西
"month","whatever1count","whatever2count"
1,null,5
2,null,3
3,null,null
4,2,3
5,36,73
6,2,null
7,45,944
8,null,12
9,1467,3
10,null,2
11,3,25
12,4,null

编辑 - 基本上哪里有一个灵活的方式来获取我的月份列表/表格/无论

2 个答案:

答案 0 :(得分:4)

许多方法......在之前的工作中,在许多应用程序中运行良好的方法是构建一个时间表表。

id - Year - Month   - StartStamp            - End Stamp  
1  - 2008 - January - 1/1/2008 00:00:00.000 - 1/31/2008 23:59:59.999

然后你可以加入时间帧表,你的日期字段在startstamp和endstamp之间。

这样可以轻松拉出特定时间段或所有时间段......

你的可能会更简单,只有12条记录(即1月1日)并加入DATEPART(m,DateColumn)

select mon.monthNumber, mon.monthName, 
       count(a.*) as count1, count(b.*) as count2
from months mon
left join whatever1 a on DATEPART(m,a.Date) = mon.monthNumber
left join whatever2 b on DATEPART(m,b.Date) = mon.monthNumber
group by mon.monthNumber, mon.monthName

你也可以临时做月事,如下:

select mon.monthNumber, mon.monthName, 
       count(a.*) as count1, count(b.*) as count2
from (
   select 1 as monthNumber, 'January' as monthName
   union
   select 2 as monthNumber, 'February' as monthName
   union
   select 3 as monthNumber, 'March' as monthName
   union
   ......etc.....
) mon
left join whatever1 a on DATEPART(m,a.Date) = mon.monthNumber
left join whatever2 b on DATEPART(m,b.Date) = mon.monthNumber
group by mon.monthNumber, mon.monthName

答案 1 :(得分:4)

  

基本上哪里有光滑的方式   我的月份清单/表格/无论

您可以使用递归cte来构建月份列表。

;with Months(MonthNum) as
(
  select 1 MonthNum
  union all
  select MonthNum+1
  from Months
  where MonthNum < 12 
)

-- Your query goes here
select * 
from Months