sql如果语句不起作用

时间:2018-05-22 14:13:14

标签: sql if-statement

我无法得到这个if语句。 我试图说'if(日期数)大于330,返回'x',否则给我(日期数)

SELECT     if(ROUND(COUNT(ClosedDate) / 10, 0) * 10 > 330 then 'X' else ROUND(COUNT(ClosedDate) / 10, 0) * 10) end AS [Previous Day Sales]
FROM         PartsSales
WHERE     (MONTH(ClosedDate) = MONTH(GETDATE())) 
AND       (YEAR(ClosedDate) = YEAR(GETDATE())) 
AND       (DAY(ClosedDate) = DAY(GETDATE() - 13))

3 个答案:

答案 0 :(得分:0)

使用CASE子句:

SELECT     CASE WHEN ROUND(COUNT(ClosedDate) / 10, 0) * 10 > 330 then 'X' else ROUND(COUNT(ClosedDate) / 10, 0) * 10 end AS [Previous Day Sales]
FROM         PartsSales
WHERE     (MONTH(ClosedDate) = MONTH(GETDATE())) AND (YEAR(ClosedDate) = YEAR(GETDATE())) AND (DAY(ClosedDate) = DAY(GETDATE() - 13))

答案 1 :(得分:0)

使用CASE:

SELECT
CASE WHEN ROUND(COUNT(ClosedDate) / 10, 0) * 10 > 330
THEN 'X' ELSE ROUND(COUNT(ClosedDate) / 10, 0) * 10) END AS [Previous Day Sales]
FROM PartsSales
WHERE MONTH(ClosedDate) = MONTH(GETDATE())
AND YEAR(ClosedDate) = YEAR(GETDATE())
AND DAY(ClosedDate) = DAY(GETDATE() - 13)

答案 2 :(得分:0)

我建议:

SELECT (CASE WHEN COUNT(*) >= 335 THEN 'X'
             ELSE CAST(ROUND(COUNT(ClosedDate) / 10, 0) * 10) as VARCHAR(255))
        END) AS [Previous Day Sales]
FROM PartsSales ps
WHERE CAST(ClosedDate as DATE) = CAST(DATEADD(day, -13, GETDATE()) as DATE);

注意:

  • WHERE条款太复杂了。
  • 为什么"前一天"使用13天前的一天?
  • 明确表示类型!你正在混合字符串和数字。 case表达式的结果必须是字符串。