Sql query for month wise
I was trying on a sql query where we have search on month wise
for example my table is like
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
Now if i want to search the users for no of visited between Feb to April i need to get output as
Users Nov_2010 Dec_2010 Jan_2011 Feb_2011 March_2011
A 1 1 0 1 开发者_运维问答 2
B 1 2 0 1 1
Please let me know the way to proceed.
Thanks
I'm afraid you have to make use of dynamic 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)
There it´s a solution based on 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;
精彩评论