sql查询每月结果但如何?

时间:2009-06-09 14:10:24

标签: sql sql-server sql-server-2005 tsql

此查询首先在表格下方返回。例如; 2009-06-01 00:00:00人们进入我的系统'41'次。我需要第二张表

 declare @date1 smalldatetime, @date2 smalldatetime , @countgap int, @page nvarchar(100)   
select @date1='2009-01-01', @date2='2009-12-30 23:59:59' ,@countgap=1, @page='Tüm Sayfalar'

declare @@date1 smalldatetime,@@date2 smalldatetime , @COUNT INT          
   select @@date1=@date1, @@date2=@date2 , @COUNT=1          
   select @@date1 TARIH , @COUNT SIRA           
  INTO #TMP          
  WHILE @@date1 < @@date2           
BEGIN           
   SELECT  @@date1 = DATEadd(month,@countgap,@@date1) , @COUNT = @COUNT +1          
   INSERT INTO #TMP          
   select @@date1 TARIH , @COUNT SIRA           
END  
  select t1.TARIH, t1.SIRA, VISITINGCOUNT = isnull(t2.TARIH, 0)          
   from #TMP t1          
   left join ( 
    select count(page) as TARIH,             
      datepart(month,Date) as SIRA           
    from scr_StatisticaLog            
    where Date between @date1 and  @date2  and 
         (Page=@page or @page='Tüm Sayfalar') and 
          ProcessType='PageView'       
    GROUP BY datepart(month,Date)
             )t2 on t2.SIRA = t1.SIRA          
    order by t1.SIRA          
  return     

2009-01-01 00:00:00 1   0
2009-02-01 00:00:00 2   0
2009-03-01 00:00:00 3   0
2009-04-01 00:00:00 4   1
2009-05-01 00:00:00 5   1
2009-06-01 00:00:00 6   41
2009-07-01 00:00:00 7   0
2009-08-01 00:00:00 8   0
2009-09-01 00:00:00 9   0
2009-10-01 00:00:00 10  0
2009-11-01 00:00:00 11  0
2009-12-01 00:00:00 12  1
2010-01-01 00:00:00 13  0


2009-January        12  1

3 个答案:

答案 0 :(得分:1)

使用DATENAME and DATEPART functions格式化日期:

SELECT 
  DATEPART(year,DateColumn) + '-' + DATENAME(month,DateColumn) AS FormattedDate
FROM
  Table

答案 1 :(得分:0)

您需要的是calendar table,其中包含每个日期。之后你就离开了,加入了第二张桌子。

编辑:啊......来自海报的新信息使这个答案无效......

答案 2 :(得分:0)

Welbog的回答有效。

我会走得更远。在MySQL的土地上,我只是在约会时做了一个左(10),并按此分组。然后,您可以在没有临时表或循环的一次传递中执行整个查询。我认为SQL服务器会让你对日期进行子字符串,但如果没有,你可以通过建立日期来做到这一点,正如Welbog向你展示的那样。