我需要為標記為我的查詢創建一個新列 Tags
共有三個標簽,定義如下:
地鐵:城市 = 芝加哥
郵寄:ACNT = 'ACT'
問候語:稱呼(“女士”,“女士”)
當前表:
ID Salutation City State ACNT
01 Ms. Delray Beach FL
02 Mrs. Lauderhill FL DCT
03 Ms. New York NY
04 Ms. Chicago IL ACT
05 Chicago IL ACT
我需要在我的輸出中添加一列標簽,就像這樣。
ID Salutation City State ACNT Tags
01 Ms. Delray Beach FL Greeting
02 Mrs. Lauderhill FL DCT Greeting
03 Ms. New York NY Greeting
04 Ms. Chicago IL ACT Metro, Greeting, Mailing
05 Chicago IL ACT Metro, Mailing
我以前用過Stuff,但不是這種方式。任何幫助/指導將不勝感激。
uj5u.com熱心網友回復:
如果您使用的是最新版本的 Oracle,您可以使用帶有派生標簽表的交叉應用(使用 case 運算式,如@serfe 建議的那樣):
select id, salutation, city, state, acnt, tag
from your_table
cross apply (
select case when city = 'Chicago' then 'Metro' end as tag from dual
union all
select case when salutation in ('Ms.', 'Mrs.') then 'Greeting' end as tag from dual
union all
select case when acnt = 'ACT' then 'Mailing' end as tag from dual
)
然后使用listagg()以您想要的形式獲取串列:
select id, salutation, city, state, acnt,
listagg (tag, ', ') within group (order by null) as tags
from your_table
cross apply (
select case when city = 'Chicago' then 'Metro' end as tag from dual
union all
select case when salutation in ('Ms.', 'Mrs.') then 'Greeting' end as tag from dual
union all
select case when acnt = 'ACT' then 'Mailing' end as tag from dual
)
group by id, salutation, city, state, acnt
| ID | 敬禮 | 城市 | 狀態 | 碳納米管 | 標簽 |
|---|---|---|---|---|---|
| 03 | 多發性硬化癥。 | 紐約 | 紐約 | 空值 | 問候 |
| 01 | 多發性硬化癥。 | 德拉海灘 | FL | 空值 | 問候 |
| 02 | 太太。 | 勞德希爾 | FL | 離散余弦變換 | 問候 |
| 04 | 多發性硬化癥。 | 芝加哥 | 伊利諾伊州 | 行為 | 地鐵,問候,郵寄 |
| 05 | 空值 | 芝加哥 | 伊利諾伊州 | 行為 | 地鐵、郵寄 |
資料庫<>小提琴
uj5u.com熱心網友回復:
的運算式為TAGS:
RTRIM(
CASE WHEN salutation IN ('Ms.','Mrs.') THEN 'Greeting' || ', ' ELSE '' END ||
CASE WHEN city = 'Chicago' THEN 'Metro' || ', ' END ||
CASE WHEN acnt = 'ACT' THEN 'Mailing' END
,', ')
您可以在UPDATE陳述句中使用該運算式來設定新TAGS列的值。或者,您可以將它放在視圖或 SQL 查詢或虛擬列中以TAGS根據需要計算值。
uj5u.com熱心網友回復:
您可以使用 CASE - WHEN 陳述句來完成。更多資訊在這里:https : //www.w3schools.com/sql/sql_case.asp
uj5u.com熱心網友回復:
如果您對標簽的外觀略有不同,那么concat使用它會變得更容易||
select t.*, case when city='Chicago' then '(Metro)' else '' end ||
case when salutation in ('Ms.','Mrs.') then '(Greeting)' else '' end ||
case when acnt = 'ACT' then '(Mailing)' else '' end as tags
from your_table t;
輸出
| ID | 敬禮 | 城市 | 狀態 | 碳納米管 | 標簽 |
|---|---|---|---|---|---|
| 01 | 多發性硬化癥。 | 德拉海灘 | FL | (問候) | |
| 02 | 太太。 | 勞德希爾 | FL | 離散余弦變換 | (問候) |
| 03 | 多發性硬化癥。 | 紐約 | 紐約 | (問候) | |
| 04 | 多發性硬化癥。 | 芝加哥 | 伊利諾伊州 | 行為 | (地鐵)(問候)(郵寄) |
| 05 | 芝加哥 | 伊利諾伊州 | 行為 | (地鐵)(郵寄) |
通過對 Matthew 的出色解決方案稍加調整,您還可以執行以下操作以準確獲得您想要的
select t.*, ltrim(case when city='Chicago' then 'Metro' else '' end ||
case when salutation in ('Ms.','Mrs.') then ',Greeting' else '' end ||
case when acnt = 'ACT' then ',Mailing' else '' end,',') as tags
from your_table t
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/388828.html
