这是我的问题:
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
的所有值。以上查询似乎对我来说是完美的,但我不知道为什么它不起作用。
答案 0 :(得分:3)
这是因为ELSE
部分,返回值转换为DECIMAL
(或任何数据类型SourceDocDr
)。请记住,在CASE
表达式中,如果返回值具有不同的数据类型,则它们将转换为具有较高data type precedence.
来自CASE
文档:
从中输入类型集中的最高优先级类型 result_expressions和可选的else_result_expression。
要获得所需的结果,您必须CAST
将CASE
表达式的结果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