我想返回一个字符串(-)破折号,或者当返回值是NULL或零时返回空值,下面是查找结果,第一列([Total 1])是原始SUM()查询,第二列列([总计2])是我想要的结果,它可以正常工作,但是代码重复并且看上去很笨,有没有更干净的方法?
SELECT
SUM(CASE
WHEN ( DATEDIFF(day,OrderDate,GETDATE()) = 0 ) THEN 1
WHEN ( DATEDIFF(day,BookingDate,GETDATE()) = 0 ) THEN 1
END) AS [Total 1],
(CASE
WHEN (SUM(CASE
WHEN ( DATEDIFF(day,OrderDate,GETDATE()) = 0 ) THEN 1
WHEN ( DATEDIFF(day,BookingDate,GETDATE()) = 0 ) THEN 1
END) IS NULL)
THEN '-'
ELSE
CAST(SUM(CASE
WHEN ( DATEDIFF(day,OrderDate,GETDATE()) = 0 ) THEN 1
WHEN ( DATEDIFF(day,BookingDate,GETDATE()) = 0 ) THEN 1
END) AS VARCHAR(20))
end
) AS [Total 2]
FROM TABLE
谢谢。
答案 0 :(得分:1)
您必须将值转换为字符串。如果使用CASE
表达式,则需要重复SUM()
。另一种方法是嵌套NULLIF()
和COALESCE()
:
COALESCE(NULLIF(CONVERT(VARCHAR(255),
SUM(CASE WHEN ( DATEDIFF(day,OrderDate,GETDATE()) = 0 ) THEN 1
WHEN ( DATEDIFF(day,BookingDate,GETDATE()) = 0 ) THEN 1
END), 0
)
), '-'
) AS [Total 1],
这种类型的操作在SQL中非常麻烦。通常,最好在应用程序级别完成。