我是 PostgreSQL 新手。我有一個包含三列的表,如下所述,我想將標題行轉換為另一列中具有相應值的列,最后是一個新列,用于檢查值是否丟失。
ID NAME EMAIL SALARY
1 John '' 1000
2 Sam feeeee@asd.com 6000
3 Tom aeesde@asd.com 9000
4 Bob mnnke@asd.com 500
5 Lari kllewl@asd.com 3000
每個 ID 的預期輸出:
ID fields Value Verified
1 NAME John Yes
EMAIL '' No
SALARY 1000 Yes
2 NAME Sam Yes
EMAIL feeeee@asd.com Yes
SALARY 6000 Yes
uj5u.com熱心網友回復:
另一種選擇是使用帶有 VALUES 子句的 CROSS JOIN 將列轉換為行:
select t.id,
u.*,
case
when u.value = '' or u.value is null then 'No'
else 'Yes'
end as verified
from the_table t
cross join lateral (
values ('NAME', name), ('EMAIL', email), ('SALARY', salary::text)
) as u(column_name, value)
order by t.id, u.column_name
這寫起來更短,更容易維護,但我看到 Thorsten Kettner 的 UNION ALL 方法在某些情況下更快。
uj5u.com熱心網友回復:
您所說的標題行根本不是行,而只是列名。您希望每個 ID 和列有一行。雖然這是我寧愿在應用程式中而不是在 SQL 中做的事情,但這當然是可能的。每列需要一個查詢。將他們的結果與UNION ALL.
select
id,
'NAME' as fields,
name as value,
case when name is null or name = '' then 'No' else 'Yes' as verified
from mytable
union all
select
id,
'EMAIL' as fields,
email as value,
case when email is null or email = '' then 'No' else 'Yes' as verified
from mytable
union all
select
id,
'SALARY' as fields,
cast(salary as varchar) as value,
case when salary is null then 'No' else 'Yes' as verified
from mytable
order by id, fields;
但如前所述,最好只select * from mytable關注應用程式中資料的呈現方式。這也可能快得多。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/439639.html
標籤:sql PostgreSQL 不枢轴
下一篇:致命錯誤:未捕獲的錯誤:無法訪問受保護的屬性Lin\Binance\Exceptions\ExceptionPHP
