SQL Server - 来自不同表的2个日期之间的日期

时间:2017-11-06 17:41:01

标签: sql sql-server

我遇到一个问题,我在下面的case语句中一直得到null(或0,如果我使用isnull函数)。我想说当一个表的ord_due_date在另一个表的两个日期之间时,返回一个值。我不确定为什么它继续返回null值。谁能告诉我我做错了什么?

+cast(isnull(CASE
WHEN year(ord_due_date)=cal_yr and ord_due_date<=prd01_end_date 
    THEN '01 '+year(ord_due_date)
WHEN year(ord_due_date)=cal_yr and ord_due_date>prd01_end_date AND ord_due_date<=prd02_end_date
    THEN '02 '+year(ord_due_date)
WHEN year(ord_due_date)=cal_yr and ord_due_date>prd02_end_date AND ord_due_date<=prd03_end_date
    THEN '03 '+year(ord_due_date)
WHEN year(ord_due_date)=cal_yr and ord_due_date>prd03_end_date AND ord_due_date<=prd04_end_date
    THEN '04 '+year(ord_due_date)
WHEN year(ord_due_date)=cal_yr and ord_due_date>prd04_end_date AND ord_due_date<=prd05_end_date
    THEN '05 '+year(ord_due_date)
WHEN year(ord_due_date)=cal_yr and ord_due_date>prd05_end_date AND ord_due_date<=prd06_end_date
    THEN '06 '+year(ord_due_date)
WHEN year(ord_due_date)=cal_yr and ord_due_date>prd06_end_date AND ord_due_date<=prd07_end_date
    THEN '07 '+year(ord_due_date)
WHEN year(ord_due_date)=cal_yr and ord_due_date>prd07_end_date AND ord_due_date<=prd08_end_date
    THEN '08 '+year(ord_due_date)
WHEN year(ord_due_date)=cal_yr and ord_due_date>prd08_end_date AND ord_due_date<=prd09_end_date
    THEN '09 '+year(ord_due_date)
WHEN year(ord_due_date)=cal_yr and ord_due_date>prd09_end_date AND ord_due_date<=prd10_end_date
    THEN '10 '+year(ord_due_date)
WHEN year(ord_due_date)=cal_yr and ord_due_date>prd10_end_date AND ord_due_date<=prd11_end_date
    THEN '11 '+year(ord_due_date)
WHEN year(ord_due_date)=cal_yr and ord_due_date>prd11_end_date AND ord_due_date<=prd12_end_date
    THEN '12 '+year(ord_due_date)
WHEN year(ord_due_date)=cal_yr and ord_due_date>prd12_end_date AND ord_due_date<=prd13_end_date
    THEN '13 '+year(ord_due_date)
END,0) as varchar(40))+'    '+

编辑:从这些列中添加数据

Ord_Due_Date(日期)

enter image description here

Cal_Yr(数字)和Prd_End_Date(日期)

enter image description here

2 个答案:

答案 0 :(得分:0)

我想你必须直接使用isnull到日期字段而不是整个查询

例如

情况下 WHEN年(isnull(ord_due_date,0))= isnull(cal_yr,0)和isnull(ord_due_date,0)&lt; = isnull(prd01_end_date,0)那么'01'+年( isnull(ord_due_date,0)< /强>)

答案 1 :(得分:0)

我必须连接并将我的THEN语句的每一部分转换为varchar才能工作。它不喜欢我使用数字并将其与日期相结合。

那么concat(cast('11'作为varchar(10)),'',cast(年(ord_due_date)作为varchar(10)))