1

我有一个 SQL 语句来确定两个日期之间的天数。如果差值为负,则语句需要选择 0。该语句有效,但我想知道是否可以将值分配给datediff("D",GETDATE(),dbo.tblKBX_Reward.validdate)@ 变量,这样我就不必调用它两次。

SELECT CASE 
WHEN datediff("D",GETDATE(),dbo.tblKBX_Reward.validdate) < 0  THEN 0
ELSE datediff("D",GETDATE(),dbo.tblKBX_Reward.validdate)
END from ...

请不要问我为什么要使用 SQL 而不是代码来计算这个值。

谢谢

4

5 回答 5

3

你可以写一个更高级别的SELECT东西。

SELECT CASE 
       WHEN diff_date < 0  THEN 0
       ELSE diff_date
       END 
FROM (
     SELECT datediff("D",GETDATE(),dbo.tblKBX_Reward.validdate) AS diff_date
     from ...
     )
于 2012-05-25T18:09:46.030 回答
3

您可以在计算中移动 case 语句,如下所示:

Select DateDiff("D", GetDate(), Case When YourColumn > GetDate() 
                                     Then YourColumn 
                                     Else GetDate() 
                                     End)
于 2012-05-25T18:18:00.970 回答
1

如果您选择多行,则不能将其分配给变量。在您的情况下,您可以使用派生表或 CTE:

SELECT  Cols, 
        CASE 
        WHEN DiffDates < 0  THEN 0
        ELSE DiffDates
        END DiffDates
FROM (  SELECT Cols, datediff("D",GETDATE(),dbo.tblKBX_Reward.validdate) DiffDates
        FROM dbo.tblKBX_Reward) A

或者:

;WITH CTE AS
(
    SELECT Cols, datediff("D",GETDATE(),dbo.tblKBX_Reward.validdate) DiffDates
    FROM dbo.tblKBX_Reward
)

SELECT  Cols, 
        CASE 
        WHEN DiffDates < 0  THEN 0
        ELSE DiffDates
        END DiffDates
FROM CTE
于 2012-05-25T18:10:08.963 回答
1
SELECT
  CASE WHEN daydiff < 0 THEN 0 ELSE daydiff END
FROM your tables/joins
CROSS APPLY (
  SELECT DATEDIFF(DAY, GETDATE(), dbo.tblKBX_Reward.validdate)
) x (daydiff)
WHERE …
于 2012-05-25T18:23:29.143 回答
0

您可以使用 CTE:

WITH cte_dateDiffs (RewardId, dateDiff) 
AS (
   SELECT RewardId, datediff("D",GETDATE(), validdate) FROM dbo.tblKBX_Reward
)
SELECT CASE 
   WHEN dd.dateDiff < 0 THEN 0 
   ELSE dd.dateDiff 
END
FROM dbo.tblKBX_Reward r
INNER JOIN cte_dateDiffs dd ON r.RewardId == dd.RewardId
...
于 2012-05-25T18:14:14.827 回答