I want to add the columns based on different date range and then I want to place the corresponding sum for each date range into a view.
I have a table like below:
Date_From Available
01/03/2011 5
06/03/2011 6
25/03/2011 7
14/04/2011 9
20/04/2011 10
I want output in a view like this:
Q3 Q4
Sum 18 19
where Q3 and Q4 are the total record for month of March and April .
Can somebody tell me what I should do?
I'm going to assume that you are not solely concerned with just March and April, and that what you really want is a monthly rollup of totals, each in its own column. Since you are on SQL Server 2005, you can do this with a dynamic PIVOT
. The following code is tested and should return you the totals for each month in a separate column. I added the year as well in case you are running this over multiple years worth of data. You can change the column headings by altering the generated date string, although you must take care to make them unique and to correspondent with the column grouping you want:
CREATE TABLE ##Tab (date_from datetime, available int)
INSERT INTO ##Tab (date_from, available) VALUES ('3/1/2011', 5)
INSERT INTO ##Tab (date_from, available) VALUES('3/6/2011', 6)
INSERT INTO ##Tab (date_from, available) VALUES('3/25/2011', 7)
INSERT INTO ##Tab (date_from, available) VALUES('4/14/2011', 9)
INSERT INTO ##Tab (date_from, available) VALUES('4/20/2011', 10)
DECLARE @month_year varchar(2000)
SELECT @month_year = STUFF(
( SELECT DISTINCT '],[' + CAST(datepart(mm, date_from) AS varchar) +
'/' + CAST(datepart(yy, date_from) AS varchar)
FROM ##Tab
ORDER BY '],[' + CAST(datepart(mm, date_from) AS varchar) +
'/' + CAST(datepart(yy, date_from) AS varchar)
FOR XML PATH('')
), 1, 2, '') + ']'
DECLARE @dyn_pivot nvarchar(max)
SET @dyn_pivot =
N'
SELECT *
FROM
(
SELECT CAST(datepart(mm, date_from) AS varchar) + ''/'' + CAST(datepart(yy, date_from) AS varchar) dt, SUM(available) AS available
FROM ##Tab
GROUP BY CAST(datepart(mm, date_from) AS varchar) + ''/'' + CAST(datepart(yy, date_from) AS varchar)
) AS SourceTable
PIVOT
(
AVG(available)
FOR dt IN (' + @month_year + N')
) AS PivotTable
'
EXEC (@dyn_pivot)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.