如果有多个那么情况

时间:2016-04-15 13:21:41

标签: mysql sql report reporting

目前,报告目的是 3个不同的列中的以下数据:

//Number
                'CASE WHEN should_be.sh = "50"
                        THEN
                            REPLACE(SUBSTRING_INDEX(account.code,".",1)," ","")
                        ELSE
                            "500."
                    END',
// Account
                    'CASE WHEN should_be.sh = "50"
                            THEN
                            REPLACE(
                                SUBSTRING(SUBSTRING_INDEX(account.code,".",2),
                                    INSTR(account.code, ".") + 1)
                            ," ","")
                        ELSE
                            "92145000000"
                    END',
// Costsnumber
                        'CASE WHEN should_be.sh = "50"
                                THEN
                                    CASE WHEN LENGTH(account.code) < 15
                                        THEN
                                            REPLACE(
                                                SUBSTRING_INDEX(account.code,".",-1)
                                            ," ","")
                                        ELSE
                                            ""
                                    END
                                ELSE
                                    ""
                            END',

如果每个条件都满足ELSE,则3列看起来像这样:

+--------+-------------+------------+
| number |   account   | costnumber |
+--------+-------------+------------+
|    500 | 92145000000 |            |
+--------+-------------+------------+

如何组合3列,所以我会有一个这样的列(例如在ELSE案例中:

+-------------------------+
|        combined         |
+-------------------------+
| 500-92145000000-(empty) |
+-------------------------+

1 个答案:

答案 0 :(得分:1)

只需使用concat_ws()

CONCAT_WS('-',
          (CASE WHEN should_be.sh = '50'
                THEN REPLACE(SUBSTRING_INDEX(account.code, '.', 1), ' ', '')
                ELSE '500.'
           END),
          (CASE WHEN should_be.sh = '50'
                THEN REPLACE(SUBSTRING(SUBSTRING_INDEX(account.code, '.',2),
                                    INSTR(account.code, '.') + 1), ' ', '')
                ELSE '92145000000'
           END),
          (CASE WHEN should_be.sh = '50' AND LENGTH(account.code) < 15
                THEN REPLACE(SUBSTRING_INDEX(account.code, '.', -1), ' ', '')
                ELSE ''
           END)
         )

如果你想要&#34;(空)&#34;要真正显示第三个元素,然后用ELSE ''替换最终的ELSE '(empty)'