我如何获得所有月份从日期形式sql?

时间:2013-09-06 06:10:30

标签: c# sql sql-server crystal-reports

我的表名为'payroll',包含以下数据

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

我想在存储过程的水晶报表中得到以下结果我想要一个显示此结果的SQL查询

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

请帮助进行查询。

提前致谢

4 个答案:

答案 0 :(得分:3)

尝试更改您的查询 -

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 ....

答案 1 :(得分:2)

在SQL Server中,您可以这样做:

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

答案 2 :(得分:1)

你可能需要这样的东西。

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

答案 3 :(得分:0)

您可以创建另一个包含所有12个月的表格。然后使用payroll表执行外连接。