How I get all Month From Date form sql?

回眸只為那壹抹淺笑 提交于 2019-12-23 03:23:02

问题


I have table names 'payroll' with following data

month , pay
January , 1200
March , 1500
December , 2000

I want the following result in crystal report from stored procedure i want a SQL query that Display this result

Janury , 1200
February , 000
March , 1500
April , 000
May , 000
June , 000
July , 000
August , 000
September , 000
October , 000
November , 000
December , 2000

Please help to make the query.

Thanks in advance


回答1:


You can create another table with all 12 months in it. Then perform a outer join with with payroll table.




回答2:


Try to change your query -

SELECT [month], pay = ISNULL(pay, 0) 
FROM (
    VALUES
        ('January'),
        ('February'),
        ('March'),
        ('April'),
        ('May'),
        ('June'),
        ('July'),
        ('August'),
        ('September'),
        ('October'),
        ('November'),
        ('December')
) t([month])
LEFT JOIN <your_table> ON ....



回答3:


In SQL server you can do like this:

WITH Months AS (
              SELECT 'January' AS MonthName
    UNION ALL SELECT 'February'
    UNION ALL SELECT 'March'  
    ...
)
SELECT Months.MonthName
      ,COALESCE(Payroll.Pay, 0)
FROM Months
     LEFT JOIN Payroll
         ON Months.MonthName = Payroll.Month



回答4:


You may neeed something like this.

declare @monthno int
declare @month varchar(50)

create table #month_tmp 
    ( mont varchar(20) null,number int null) 

set @monthno = 1
while @monthno < 13
begin
    SET @month=DateName(Month,cast(@monthno as varchar) + '-01-2001')

   insert into #month_tmp
    select @month, 0

    set @monthno = @monthno + 1
end

select [month],pay from payroll
union
select mont,number
from #month_tmp

drop table #month_tmp


来源:https://stackoverflow.com/questions/18651051/how-i-get-all-month-from-date-form-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!