我有一个包含type
字段的表格。
如何在查询中检查此字段:
如果type
=='a'
然后bes
= amount
,bed
=' - '
ELSE bed
= amount
,bes
=' - '
这是我的尝试:
SELECT billing.*,
CASE billing.type WHEN 'A' THEN billing.amount AS bes, '-' AS bed ELSE billing.amount AS bed, '-' AS bes END
FROM billing
...我的搜索无效
任何解决方案......
答案 0 :(得分:5)
您可以为每一行创建条件,MySQL
支持内嵌 IF
语句。
SELECT billing.*,
IF(billing.type = 'A', billing.amount, '-') AS bes,
IF(billing.type = 'A', '-', billing.amount) AS bed
FROM billing
答案 1 :(得分:4)
你需要两个案例陈述:
SELECT billing.*,
CASE billing.type WHEN 'A' THEN billing.amount ELSE '-' AS bes END,
CASE billing.type WHEN 'A' THEN '-' ELSE billing.amount AS bed END
FROM billing
答案 2 :(得分:3)
一个CASE-WHEN-THEN-ELSE
只能有一个返回值......
这应该可以解决问题:
SELECT billing.*,
CASE billing.type WHEN 'A' THEN billing.amount ELSE '-' END AS bes,
CASE billing.type WHEN 'A' THEN '-' ELSE billing.amount END AS bed
FROM billing
答案 3 :(得分:3)
SELECT billing.*,
CASE WHEN billing.type = 'A' THEN billing.amount ELSE 0 END AS bes,
CASE WHEN billing.type <> 'A' THEN billing.amount ELSE 0 END AS bed
FROM billing
答案 4 :(得分:2)