如何将选择语句转换为多列输出

时间:2018-10-18 13:29:54

标签: sql sql-server

我有以下选择语句

SELECT 
  [Id],
  [Name],
  [Language],
  [Value]
FROM [dbo].[Translations]

结果:

Id  Name            Language Value
----------------------------------
1   Role - Singular en  Role
1   Role - Singular de  Role
1   Role - Singular nl  Rol
1   Role - Singular pl  Rola
2   Role - Plural   pl  Role
2   Role - Plural   nl  Rollen
2   Role - Plural   en  Roles
3   User - Singular en  User
3   User - Singular nl  Gebruiker
3   User - Singular de  Benutzer
3   User - Singular pl  Użytkownik
4   User - Plural   pl  Użytkownicy
4   User - Plural   nl  Gebruikers
4   User - Plural   en  Users

如何转换为该输出

Id  Name            English Dutch       Polish      German
------------------------------------------------------------
1   Role - Singular Role    Rol         Rola        Role
2   Role - Plural   Roles   Rollen      Role        NULL
3   User - Singular User    Gebruiker   Użytkownik  Benutzer
4   User - Plural   Users   Gebruikers  Użytkownicy NULL

能请你帮忙吗?我没有任何代码可以显示我的尝试,因为我是sql的初学者。 语言可能只有4列(英语,荷兰语,波兰语,德语)

1 个答案:

答案 0 :(得分:1)

您还可以使用下面的CASE语句,其中列的数目是有限的并且是固定的

select
  [Id],
  [Name],
  max(English) as English,
  max(Dutch) as Dutch,
  max(Polish) as Polish,
  max(German) as German
from (
    SELECT 
      [Id],
      [Name],
      case when [Language] = 'en' then [Value] end as English ,
      case when [Language] = 'nl' then [Value] end as Dutch  ,
      case when [Language] = 'pl' then [Value] end as Polish ,
      case when [Language] = 'de' then [Value] end as German 
    FROM [dbo].[Translations]
) t
group by
  [Id],
  [Name]