我有这个简单的桌子。
City Country State Id
Great Falls (null) VA 12345
Great Falls USA VA 12345
我想将CONCAT函数用于城市+国家+州,并在下面的Oracle环境中运行代码。
SELECT City, Country, State,
City ||', ' ||Country|| ', '||State AS Concat_fields
FROM #TEMP
City Country State Concat_fields Id
Great Falls (null) VA Great Falls, , VA 12345
Great Falls USA VA Great Falls, USA, VA 12345
问题:查询是否可以以仅返回1条记录的方式进行更改是否更好?我想显示这样的结果:
City Country State Concat_fields Id
Great Falls USA VA Great Falls, USA, VA 12345
有什么想法,批评和建议吗?
答案 0 :(得分:2)
如果行之间的唯一区别是null值与非null值,则可以在连接之前使用汇总:
-- CTE for sample data
with "#TEMP" (city, country, state, id) as (
select 'Great Falls', null, 'VA', 12345 from dual
union all select 'Great Falls', 'USA', 'VA', 12345 from dual
)
-- actual query
select max(city) as city, max(country) as country, max(state) as state,
max(city) ||', ' ||max(country)|| ', '||max(state) as concat_fields
from "#TEMP"
group by id;
CITY COU ST CONCAT_FIELDS
----------- --- -- --------------------
Great Falls USA VA Great Falls, USA, VA
如果ID的行具有不同的非null值,则显然不起作用:
with "#TEMP" (city, country, state, id) as (
select 'Great Falls', null, 'VA', 12345 from dual
union all select 'London', 'UK', null, 12345 from dual
)
select max(city) as city, max(country) as country, max(state) as state,
max(city) ||', ' ||max(country)|| ', '||max(state) as concat_fields
from "#TEMP";
CITY CO ST CONCAT_FIELDS
----------- -- -- -------------------
London UK VA London, UK, VA
,但是您将需要某种方法来确定哪一行是正确的-例如如果它代表客户的地址历史记录,并且您想要“最新”版本,则从序列或日期列中获取。然后,诀窍就是知道如何确定哪个是“最新”。
答案 1 :(得分:0)
SELECT City, Country, State,
City ||', ' ||Country|| ', '||State AS Concat_fields
FROM #TEMP
WHERE Country IS NOT NULL
这将适用于提供的数据集。
通常说来,尽管Id是唯一的(主键),所以请确保以符合更广泛接受的数据库实践的方式构建表。