在“函数何时起作用”的情况下产生非布尔结果

时间:2018-08-06 18:37:57

标签: sql case-when

我正在尝试创建一个查询,该查询会将结果分为不同的列。我可以找到的最佳公式是Case When函数,但它表示方程式的Then部分必须是布尔值(或正确/错误的结果)。那么,Then是否有一种方法可以计算出3-1的数字?

Case
when
    DATEDIFF(day, T0.[DocDueDate], getdate()) > 0 
    AND DATEDIFF(day, T0.[DocDueDate], getdate()) < 30 
then
(T0.[DocTotal] - T0.[PaidToDate]) 
else
    ' ' 
end
as "Greater than 1", 
Case
when
    DATEDIFF(day, T0.[DocDueDate], getdate()) > 30 
    AND DATEDIFF(day, T0.[DocDueDate], getdate()) < 60 
then
(T0.[DocTotal] - T0.[PaidToDate]) 
else
    ' ' 
end
as "Greater than 30"

4 个答案:

答案 0 :(得分:1)

您对类型兼容性有疑问。我建议您简单地使用NULL进行匹配:

(case when DATEDIFF(day, T0.[DocDueDate], getdate()) > 0 AND DATEDIFF(day, T0.[DocDueDate], getdate()) < 30 
      then (T0.[DocTotal] - T0.[PaidToDate]) 

 end) as Greater_than_1, 
(case when DATEDIFF(day, T0.[DocDueDate], getdate()) > 30  and DATEDIFF(day, T0.[DocDueDate], getdate()) < 60 
      then (T0.[DocTotal] - T0.[PaidToDate]) 
 end) as Greater_than_30

我还会猜到您打算将<= 30用于第一个条件。

答案 1 :(得分:0)

如果您使用sql server,则您的代码片段如下所示。 您必须在thenelse之后保持与在使用else之后使用字符串类型相同的数据类型,因此您必须在以后的then上进行转换

Case
when
    DATEDIFF(day, T0.[DocDueDate], getdate()) > 0 
    AND DATEDIFF(day, T0.[DocDueDate], getdate()) < 30 
then
( convert(varchar(255), T0.[DocTotal] - T0.[PaidToDate]))
else
    ' ' 
end
as Greater_than_1, 
Case
when
    DATEDIFF(day, T0.[DocDueDate], getdate()) > 30 
    AND DATEDIFF(day, T0.[DocDueDate], getdate()) < 60 
then
(convert(varchar(255), T0.[DocTotal] - T0.[PaidToDate])) 
else
    ' ' 
end
as Greater_than_30

答案 2 :(得分:0)

发现我需要将等式转换为整数,如下所示。

Case when 
    DATEDIFF(day, T0.[DocDueDate], getdate()) > 0 
    AND DATEDIFF(day, T0.[DocDueDate], getdate()) <30 
then 
    cast( (T0.[DocTotal]-T0.[PaidToDate]) as varchar(12) ) 
else 
    ' ' 
end as "Greater than 1"

答案 3 :(得分:0)

这里是您可以通过多种方法执行此操作的方法。 TSET只是生成6月1日到今天的日期进行测试。

lblsearchreminder.TextFrame.Characters.Font.Size= 20

一些示例结果:

WITH tset(td)
     AS (
     SELECT CAST('2018-08-01' AS DATE) AS td
     UNION ALL
     SELECT DATEADD(d, -1, td)
     FROM   tset
     WHERE  td > CAST('2018-06-01' AS DATE))
     -- Actual examples start here
     SELECT td
          -- Diff is just showing the difference in days so you can see the group assignements
          , DATEDIFF(d, td, GETDATE()) AS diff
          -- This column groups into < 30, 31-60, and > 60
          , CASE
                WHEN DATEDIFF(d, td, GETDATE()) < 30 THEN 1 ELSE CASE
                                                                     WHEN DATEDIFF(d, td, GETDATE()) < 60 THEN 2 ELSE 3
                                                                 END
            END three_sets
          -- this example will group  into any number of 30 day sets.
          , cast ( DATEDIFF(d, td, GETDATE()) as int) / 30 any_number_of_sets
     FROM   tset
     ORDER BY td;