SQLite结合了两列

时间:2013-01-14 18:15:29

标签: sqlite concatenation

此查询返回包含操作系统信息的两个单独的列,因为数据是基于扫描工具自动写入数据库表的,我无法手动更改列。我正在尝试编写一个将两行合并为一个的查询(使用operating_system_version行中的数据填充operating_system行的空白。

我现在的查询如下:

SELECT device_type, operating_system, operating_system_version
FROM DEVICES
WHERE user_name like '|%front-%|'
OR user_name like '|%back-%|'
OR user_name like '|%ap-%|'
OR user_name like '|%me-%|'
OR user_name like '|%mg-%|'

然后它返回:

device_type    operating_system        operating_system_version


desktop         windows xp
desktop                                 windows 7 professional
desktop         windows xp              
desktop                                 windows 7 professional

我希望它能返回这样的东西:

device_type    OS


desktop         windows xp
desktop         windows 7 professional                        
desktop         windows xp              
desktop         windows 7 professional  

我尝试过加入||如下所示,但它没有返回任何数据:

SELECT device_type, operating_system||operating_system_version
FROM DEVICES
WHERE user_name like '|%front-%|'
OR user_name like '|%back-%|'
OR user_name like '|%ap-%|'
OR user_name like '|%me-%|'
OR user_name like '|%mg-%|'                       

1 个答案:

答案 0 :(得分:4)

SELECT device_type, coalesce(operating_system,operating_system_version) AS OS
FROM DEVICES
WHERE user_name like '|%front-%|'
OR user_name like '|%back-%|'
OR user_name like '|%ap-%|'
OR user_name like '|%me-%|'
OR user_name like '|%mg-%|'

这将选择操作系统,如果为null,则选择operating_system_version并将其作为列名OS返回。

如果要连接两个字段,请尝试

SELECT device_type, coalesce(operating_system,'') || coalese(operating_system_version,'') AS OS
FROM DEVICES
WHERE user_name like '|%front-%|'
OR user_name like '|%back-%|'
OR user_name like '|%ap-%|'
OR user_name like '|%me-%|'
OR user_name like '|%mg-%|'