鉴于以下表格:
材料
+-----------------+-----------------+
|Material |Name |
+-----------------------------------+
|00000001 |Material Number 1|
|00000002 |Material Number 2|
+-----------------+-----------------+
材料名称
+---------+---------+-------------+
|Material |Language |Name |
+---------------------------------+
|00000001 |DE |Mat. Nummer 1|
|00000001 |FR |Matérial 1 |
|00000002 |SP |Mat. 1 |
+---------+---------+-------------+
如何创建将返回数据的SQL语句(MSSQL 2005 Flavor),如下所示:
+---------+---------------+---------------+----------+----------+
|Material |Name_EN |Name_DE |Name_FR |Name_SP |
+---------------------------------------------------------------+
|00000001 |Material Number|1 Mat. Nummer 1|Matérial 1|NULL |
|00000002 |Material Number|2 NULL |NULL |Mat. 1 |
+---------+---------------+---------------+----------+----------+
我使用CASE WHEN
,IS NOT NULL
等尝试了几种方法。但它总是导致单行只填充一列,即使有更多名称可用于材料。
我能做些什么来实现这个目标?
答案 0 :(得分:1)
您可以使用join
和条件聚合:
select m.materialid, m.name as Name_EN,
max(case when nm.language = 'DE' then nm.name end) as Name_DE,
max(case when nm.language = 'FR' then nm.name end) as Name_FR,
max(case when nm.language = 'SP' then nm.name end) as Name_SP
from materials m join
materialnames nm
on m.materialid = nm.materialid
group by m.materialid, m.name;