案例条件不会返回理想的结果

时间:2016-04-19 03:38:01

标签: sql sql-server

这是我的问题:

SELECT AccountTitle,
CASE
    WHEN SourceDocDR < 1
        THEN REPLACE(CAST(SourceDocDR AS int), 0, '')
    ELSE SourceDocDR
END AS 'Debit',
CASE
    WHEN SourceDocCR < 1
        THEN REPLACE(CAST(SourceDocCR AS int), 0, '')
    ELSE SourceDocCR
END AS 'Credit'

FROM tblAccounting_GL
WHERE month(PostingDate) = month(getdate())
GROUP BY AccountTitle, SourceDocDR, SourceDocCR;

ELSE声明的结果:

+----------------------------------+---------+--------+
|          Account Title           |  Debit  | Credit |
+----------------------------------+---------+--------+
| Accounts Payable                 | 0.00    | 100.00 |
| Accounts Receivable -VAT         | 0.00    | 300.00 |
| Cash in Bank BPI Mia Road  - PHP | 2600.00 | 0.00   |
+----------------------------------+---------+--------+

没有ELSE声明的结果:

+----------------------------------+-------+--------+
|          Account Title           | Debit | Credit |
+----------------------------------+-------+--------+
| Accounts Payable                 |       | NULL   |
| Accounts Receivable -VAT         |       | NULL   |
| Cash in Bank BPI Mia Road  - PHP | NULL  |        |
+----------------------------------+-------+--------+

上述查询应该用空格替换零或负值。但是,它仍然返回实际值。如果我删除ELSE语句,那只是零或负值被空格替换的时间。但是,在这种情况下,也不会返回大于0的所有值。以上查询似乎对我来说是完美的,但我不知道为什么它不起作用。

3 个答案:

答案 0 :(得分:3)

这是因为ELSE部分,返回值转换为DECIMAL (或任何数据类型SourceDocDr。请记住,在CASE表达式中,如果返回值具有不同的数据类型,则它们将转换为具有较高data type precedence.

的数据类型

来自CASE文档:

  

从中输入类型集中的最高优先级类型   result_expressions和可选的else_result_expression。

要获得所需的结果,您必须CASTCASE表达式的结果VARCHAR转换为SELECT AccountTitle, CASE WHEN SourceDocDR < 1 THEN '' ELSE CAST(SourceDocDR AS VARCHAR(MAX)) END AS 'Debit', CASE WHEN SourceDocCR < 1 THEN '' ELSE CAST(SourceDocCR AS VARCHAR(MAX)) END AS 'Credit' FROM tblAccounting_GL WHERE MONTH(PostingDate) = MONTH(GETDATE()) GROUP BY AccountTitle, SourceDocDR, SourceDocCR;

With Undrafted Players

答案 1 :(得分:0)

你可以这样试试: 由于零和负值需要空白值,因此选择空白而不是替换值

  SELECT AccountTitle,
  CASE
    WHEN SourceDocDR < 1
    THEN ''
    ELSE SourceDocDR
 END AS 'Debit',
  CASE
   WHEN SourceDocCR < 1
    THEN ''
   ELSE SourceDocCR
END AS 'Credit'

 FROM tblAccounting_GL
WHERE month(PostingDate) = month(getdate())
GROUP BY AccountTitle, SourceDocDR, SourceDocCR;

答案 2 :(得分:0)

你应该使用这个

SELECT AccountTitle,
CASE
    WHEN SourceDocDR <= 0
        THEN NULL
    ELSE SourceDocDR
END AS 'Debit',
CASE
    WHEN SourceDocCR <= 0
        THEN NULL
    ELSE SourceDocCR
END AS 'Credit'

FROM tblAccounting_GL
WHERE month(PostingDate) = month(getdate())
GROUP BY AccountTitle, SourceDocDR, SourceDocCR;

您的查询类型不一致,replace返回字符串类型,但ELSE返回SourceDocDR,这是数字typer。 请详细了解REPLACE