當其中一些值為 NULL 時,我正在嘗試查詢并正確格式化由 Oracle 中的多個值組成的地址。Coalesce() 對此效果很好,但在我添加空格/標點符號時效果不佳。
例子
address 1: 123 Main St
address 2: Apt 1
City: New York
State: NY
Postal Code: 10001
Country: USA
address 1: NULL
address 2: NULL
City: New York
State: NULL
Postal Code: 10001
Country: USA
提取完整地址時,如果值為 NULL,我想忽略后續標點符號,這樣就沒有多余的逗號/空格。
select a.address1 || ' ' || a.address2 || ', ' || a.city || ', ' || a.state || ' ' || a.postal_code || ', ' || 'USA',
Coalesce(a.address1, a.address2, a.city, a.state, a.postal_code,'USA')
from address a
- 示例 1 結果:123 Main St Apt 1, New York, NY 10001, USA
- 示例 2 結果: , New York, 10001, USA
示例 2 的預期結果:紐約,10001,美國
這只是一個示例,但是當缺少任何元素組合時,我想要一條格式仍然正確的行。
uj5u.com熱心網友回復:
您可以使用nvl2()函式將逗號和空格附加到每個列值,僅當它不為空時,然后將它們連接在一起:
select nvl2(address1, address1 || ', ', null)
|| nvl2(address2, address2 || ', ', null)
|| nvl2(city, city || ', ', null)
|| nvl2(state, state || ', ', null)
|| nvl2(postal_code, postal_code || ', ', null)
|| 'USA' as address
from address
| 地址 |
|---|
| 123 Main St, Apt 1, New York, NY, 10001, 美國 |
| 紐約,10001,美國 |
小提琴
如果您沒有在末尾添加固定的“USA”,那么您可能會得到一個尾隨逗號,您可以將其剪掉。
...除了我剛剛注意到您不想在address1和之間使用逗號address2...您可以使用嵌套來處理它nvl2():
select nvl2(address1, address1 || nvl2(address2, ' ', ', '), null)
|| nvl2(address2, address2 || ', ', null)
|| nvl2(city, city || ', ', null)
|| nvl2(state, state || ', ', null)
|| nvl2(postal_code, postal_code || ', ', null)
|| 'USA' as address
from address
| 地址 |
|---|
| 123 Main St Apt 1, New York, NY, 10001, 美國 |
| 123 Main St, New York, NY, 10001, 美國 |
| Apt 1, New York, NY, 10001, 美國 |
| 紐約,10001,美國 |
fiddle(對于上面顯示的輸出,添加的行只有address1or address2,以及 both/neither )。
uj5u.com熱心網友回復:
嘗試:
REGEXP_REPLACE('Just concat without worrying about NULL','( ,) ', '')
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/533916.html
標籤:数据库细绳甲骨文
上一篇:將std字串訪問器與ostream運算子<<一起使用
下一篇:根據用戶輸入從字串中洗掉字符
