![](/img/trans.png)
[英]how to get the column name of the greatest value by using greatest function postgresql?
[英]How to get the column name of a value in PostgreSQL?
假设我们有3个表:
表格1:
ID FrenchCity
1 Paris
2 Lille
3 Lyon
表2:
ID IntlCity
1 Lille
2 Geneva
3 Toulouse
表3:
ID BritishCity
1 London
2 Leeds
我想获得与值对应的列名。 例如,我给值Lille
,SQL应该返回Table1.FrenchCity Table2.IntlCity
。 如我所说,我想获取一个值的列名。 因此, Lille
存在于2个表中,我希望SQL返回{{table name}}.{{column name}}
如何编写查询来做到这一点?
这项工作适合您吗?
SELECT 'Table1.FrenchCity' as fieldName
FROM Table1
WHERE FrenchCity = 'Lille'
UNION ALL
SELECT 'Table2.IntlCity' as fieldName
FROM Table2
WHERE IntlCity = 'Lille'
UNION ALL
SELECT 'Table3.BritishCity' as fieldName
FROM Table3
WHERE BritishCity = 'Lille'
然后你可以使用array_agg
SELECT array_agg(fieldName)
FROM (
previous union query
) t
您最好创建一个包含3列的表格:
ID COUNTRY fieldName CITY
1 France FrenchCity Paris
2 France FrenchCity Lille
3 France FrenchCity Lyon
4 Intl IntlCity Lille
5 Intl IntlCity Geneva
6 Intl IntlCity Toulouse
等等。 然后使用查询:
SELECT country || '.' || fieldName
FROM three_col_table
WHERE CITY = 'Lille'
如果您不想使用数据库元数据,则可以使用row_to_json
和json_each_text
函数将表数据转换为一系列(column_name,column_value)对:
with
-- Demo data start
Table1(ID, FrenchCity) as (values
(1, 'Paris'),
(2, 'Lille'),
(3, 'Lyon')),
Table2(ID, IntlCity) as (values
(1, 'Lille'),
(2, 'Geneva'),
(3, 'Toulouse')),
-- Demo data end
my_data as (
select 'Table1' as tbl, j.*
from Table1 as t, json_each_text(row_to_json(t.*)) as j(fld,val)
union all
select 'Table2' as tbl, j.*
from Table2 as t, json_each_text(row_to_json(t.*)) as j(fld,val)
-- ... and so on ...
)
select *, format('%s.%s', tbl, fld) as desirede_value from my_data
where val ilike 'lille';
tbl | fld | val | desirede_value
--------+------------+-------+-------------------
Table1 | frenchcity | Lille | Table1.frenchcity
Table2 | intlcity | Lille | Table2.intlcity
(2 rows)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.