Click here to Skip to main content
15,890,579 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi All,

For the below query (sdate is column name and table name is storedata)
SQL
WITH TotalMonths AS (SELECT T1.[Month], T2.[Year]
 FROM ((SELECT DISTINCT Number AS [Month]
FROM MASTER.dbo.spt_values WHERE [Type] = 'p' AND Number BETWEEN 1 AND 12) T1 CROSS JOIN
 (SELECT DISTINCT DATEPART(year, sdate) AS [Year]
FROM storedata) T2))

SELECT CTE.[Year], CTE.[Month], ISNULL(T3.[Sum], 0) areasum
FROM TotalMonths CTE LEFT OUTER JOIN (
SELECT SUM(areasft) [Sum], DATEPART(YEAR, sdate) [Year], DATEPART(MONTH, sdate) [Month]
FROM storedata
GROUP BY DATEPART(YEAR, sdate) ,DATEPART(MONTH, sdate)) T3
ON CTE.[Year] = T3.[Year] AND CTE.[Month] = T3.[Month] WHERE CTE.[Year]>'2007'
ORDER BY CTE.[Year], CTE.[Month]

I am getting result set like below:
YEAR MONTH AREASUM
2008	1	0
2008	2	1193
2008	3	4230
2008	4	350
2008	5	2200
2008	6	4660
2008	7	0
2008	8	6685
2008	9	0
2008	10	3051
2008	11	7795
2008	12	2940
2009	1	1650
2009	2	3235
2009	3	2850
2009	4	6894
2009	5	3800
2009	6	2250
2009	7	1000
2009	8	1800
2009	9	1550
2009	10	2350
2009	11	0
2009	12	1800

But I have to combine both month and year in single column. The reult set should like below.
JAN/08 O
FEB/08 1193
.. ..
.. ..
DEC/O9 1800

How can I modify my query? (I should display for all the years and months even if there is no area for a month)

Regards,
N.SRIRAM
Posted
Updated 10-Jan-11 0:44am
v4
Comments
Sunasara Imdadhusen 10-Jan-11 4:19am    
Do you want to display "Yera/Month" from date field?

1 solution

I think there's not any inbuilt function that can provide you pattern formatted output in SQL. Yes it is available by Language at display time.

Or you can combine two result and make your things work by customizing

Like

SQL
SELECT CAST(DateName(mm,GetDate())  as varchar) + '/' + CAST(DateName(DD,GetDate())  as varchar)


You can refer DateName HERE[^] and displaying output with pattern at language side you may find THIS[^] article to be useful.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900