SQL 将两行合并为一个值
SQL combine two rows into one value
我需要合并两列的值并将值放入第三列。例如,
我有一个 table 像这样:
Name Age Key
Joe 4
Mike 10
Larry 20
我想要一个输出,其中键是姓名和年龄列的组合。
Name Age Key
Joe 4 Joe/4
Mike 10 Mike/10
Larry 20 Larry/20
如果 Name 不是空值,我只需要合并到 Key 字段中。中间加/组合。
我试过 GROUP_CONCAT 没有成功,我也试过 concat 没有成功...
select Name, Age, (CASE WHEN table.Name IS NULL OR table.Name = '' then else concat(table.Name, '/', table.Age)) as Key from table
您的查询有两个错误
SELECT Name,
Age,
( CASE
WHEN TABLE.Name IS NULL
OR TABLE.Name = '' THEN '' -- Missing then result
ELSE Concat(TABLE.Name, '/', TABLE.Age)
END ) AS KEY --END missing
FROM TABLE
Select Name, Age, case when Name is not null then Name + "/" + Age end as Key from ...
我觉得用coalesce来处理nulls比较简单
coalesce(Name + '/' + Age,'')
Coalesce 在这里也可以工作...
select Name
, Age
, concat(coalesce(table.Name,''), '/', coalesce(table.Age,''))) as Key
from table
尽管在年龄和姓名可能是 '' 时将其称为密钥似乎有风险
我需要合并两列的值并将值放入第三列。例如, 我有一个 table 像这样:
Name Age Key
Joe 4
Mike 10
Larry 20
我想要一个输出,其中键是姓名和年龄列的组合。
Name Age Key
Joe 4 Joe/4
Mike 10 Mike/10
Larry 20 Larry/20
如果 Name 不是空值,我只需要合并到 Key 字段中。中间加/组合。
我试过 GROUP_CONCAT 没有成功,我也试过 concat 没有成功...
select Name, Age, (CASE WHEN table.Name IS NULL OR table.Name = '' then else concat(table.Name, '/', table.Age)) as Key from table
您的查询有两个错误
SELECT Name,
Age,
( CASE
WHEN TABLE.Name IS NULL
OR TABLE.Name = '' THEN '' -- Missing then result
ELSE Concat(TABLE.Name, '/', TABLE.Age)
END ) AS KEY --END missing
FROM TABLE
Select Name, Age, case when Name is not null then Name + "/" + Age end as Key from ...
我觉得用coalesce来处理nulls比较简单
coalesce(Name + '/' + Age,'')
Coalesce 在这里也可以工作...
select Name
, Age
, concat(coalesce(table.Name,''), '/', coalesce(table.Age,''))) as Key
from table
尽管在年龄和姓名可能是 '' 时将其称为密钥似乎有风险