用于月份的SQL查询

时间:2011-04-13 01:11:46

标签: sql-server

我正在尝试一个sql查询,我们在月份搜索

例如我的表就像

Username   visited  Visisted_Dated

   A          1       01/11/2010
   B          1       10/11/2010
   A          1       03/12/2010
   B          1       06/12/2010
   B          1       06/12/2010
   A          1       03/02/2011 
   B          1       05/02/2011
   A          1       11/03/2011
   A          1       20/03/2011
   B          1       01/03/2011

现在,如果我想在2月到4月之间搜索没有访问过的用户,我需要输出

 Users Nov_2010  Dec_2010   Jan_2011   Feb_2011  March_2011 
   A       1         1        0           1           2               
   B       1         2        0           1           1         

请让我知道继续进行的方式。

谢谢

2 个答案:

答案 0 :(得分:2)

我担心你必须使用动态SQL:

DECLARE @Sql VARCHAR(8000)
DECLARE @ColumnNames VARCHAR(1000)
DECLARE @BeginDate DATETIME
DECLARE @EndDate DATETIME

SET @BeginDate = '2010-11-1'
SET @EndDate = '2011-4-1'
SET @ColumnNames = ''

WHILE @BeginDate <= @EndDate
BEGIN
    SET @ColumnNames = @ColumnNames + ',[' + DateName(month,@BeginDate) + '_' + Cast(Year(@BeginDate) AS VARCHAR(4)) + ']'
    SET @BeginDate = DateAdd(Month, 1, @BeginDate)
END
IF Len(@ColumnNames) > 0
    SET @ColumnNames = Right(@ColumnNames, Len(@ColumnNames) - 1)

PRINT @ColumnNames

SET @Sql = '
WITH U AS
(
    SELECT UserName, DateName(month,Visited_Dated) + ''_'' + Cast(Year(Visited_Dated) AS VARCHAR(4)) AS VisitedMonth, Visited
    FROM Users
)
SELECT *
FROM U
PIVOT (
    SUM(Visited) FOR VisitedMonth IN (' + @ColumnNames + ')
) AS P'

EXEC (@Sql)

答案 1 :(得分:0)

有一个基于PIVOT

的解决方案
SELECT UserName,[201011], [201012], [201101], [201102], [201103]
FROM
(SELECT UserName,Visited,convert(varchar(6),[Visited_Dated],112) Periodo
FROM [Table]) AS st
PIVOT
(
COUNT(Visited)
FOR Periodo IN ([201011], [201012], [201101], [201102], [201103])
) AS pt;