1

My goal is to return a row of month name with a column of Year. This is to get the sum of sales of one particular tenant in a per year and month table.

I have started to this code

select   
    month(date) month,
    isnull(sum(case when year(DATE) = 2015 then sales end), 0) as '2015'
from 
    tblSales
where 
    tenantcode = 'cmbina13'
group by  
    month(date)
order by 
    month(date)

and I get back this result:

enter image description here

The figures are correct. However I want to make month column turn into month name. Like this image below as desired output

enter image description here

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
rickyProgrammer
  • 1,177
  • 4
  • 27
  • 63
  • 1
    Take a look at this http://stackoverflow.com/questions/185520/convert-month-number-to-month-name-function-in-sql – Sateesh Pagolu Aug 07 '15 at 03:49
  • And why would you honestly want to do something like that? Let your presentation layer handle the presentation stuff. – lc. Aug 07 '15 at 03:51
  • Will it affect badly if it did it in sql? – rickyProgrammer Aug 07 '15 at 03:54
  • 1
    I agree, it is a better practice to handle the naming in presentation layer unless this is for purely reporting purposes. – Sateesh Pagolu Aug 07 '15 at 03:55
  • I understand, but there are instances where we would need to look at the back report, so it is needed to be done that way. But I already have code for doing the conversion in my presentation layer such as in ASP.NET and Crystal Report, way too easier than in SQL, since I have limited knowledge in it. – rickyProgrammer Aug 07 '15 at 05:31

2 Answers2

4

Instead of Month function use Datename function with Month datepart

select  datename(month,date) [month]
       ,isnull(sum(case when year(DATE) = 2015 then sales end), 0) as '2015'
from tblSales
where tenantcode = 'cmbina13'
group by  datename(month,date)
Order by DATEPART(MM,datename(month,date)+' 01 2011')
Pரதீப்
  • 91,748
  • 19
  • 131
  • 172
1
SELECT      DATENAME(mm, date) AS MName
            ,ISNULL(SUM(CASE WHEN YEAR(GETDATE()) = 2015 then sales end), 0) AS '2015'
FROM        tblSales
WHERE       tenantcode = 'cmbina13'
GROUP BY    DATENAME(mm, date)
order by    DATENAME(mm, date)
Gehan Fernando
  • 1,221
  • 13
  • 24