SQL将关系表组合为单独的列

时间:2016-02-03 12:02:44

标签: sql sql-server

我有这两张桌子

 Items
 ID     Type     ClientID
 ========================
 1      0        123
 2      0        123

 Texts
 ItemID   Language     Text
 ================================
 1        Eng          Hi there!
 1        Spa          Holla!
 2        Eng          bye!
 2        Spa          bye in Spanish!

在我的最终结果中,我看了SQL给我这个表格

 ID      Type    Eng           Spa
 ================================
 1       0        Hi there!     Holla!
 2       0         Bye!          bye in Spanish!

我试图创建这个声明:

 SELECT DISTINCT I.ID ,I.Type,
 (SELECT T.Text WHERE D.Language='Eng') AS 'Eng',
 (SELECT T.Text WHERE D.Language='Spa') AS 'Spa'
 FROM Items I
 INNER JOIN Texts T ON I.ID=T.ItemID

但我得到了这个结果:

 ID      Type    Eng           Spa
 ================================
 1       0        Hi there!     NULL
 1       0        NULL          Holla!
 2       0        Bye!          NULL
 2       0        NULL          bye in Spanish!

5 个答案:

答案 0 :(得分:4)

我不明白为什么需要加入。您可以使用条件聚合:

select t.itemid,
       max(case when t.language = 'Eng' then t.text end) as Eng,
       max(case when t.language = 'Spa' then t.text end) as Spa
from texts t
group by t.itemid;

答案 1 :(得分:1)

使用嵌套在具有过滤器(where子句)的同一个表上进行两次连接。 下面我已经在MySQL上测试了

SELECT 
    i.id, eng_table.text AS eng, spa_table.text AS spa
FROM
    i
        LEFT OUTER JOIN
    (SELECT 
        ItemID AS ID, Text
    FROM
        t
    WHERE
        Language = 'ENG') AS eng_table ON i.id = eng_table.id
        LEFT OUTER JOIN
    (SELECT 
        ItemID AS ID, Text
    FROM
        t
    WHERE
        Language = 'SPA') AS spa_table ON i.id = spa_table.id

此致 Bikxs

答案 2 :(得分:0)

使用连接的解决方案看起来像....

Select i.ID 
      ,i.[Type]
      ,t1.[Text] AS [Eng]
      ,t2.[Text] AS [Spa]
FROM Items i 
INNER JOIN Texts t1 ON i.ID = t1.ItemID AND t1.[Language] = 'Eng'
INNER JOIN Texts t2 ON i.ID = t2.ItemID AND t2.[Language] = 'Spa'

答案 3 :(得分:0)

WITH Eng
AS
(
    SELECT * FROM Texts t WHERE t.Language = 'Eng'
),
Spa
AS
(
    SELECT * FROM Texts t WHERE t.Language = 'Spa'
)
SELECT i.ID, i.Type, e.Text AS Eng, s.Text AS Spa
FROM Items i 
LEFT JOIN Eng e ON i.ID = e.ItemID
LEFT JOIN Spa s ON i.ID = s.ItemID

答案 4 :(得分:0)

即使您可以使用动态SQL查询。

<强>查询

DECLARE @query VARCHAR(MAX)

SELECT @query = 'SELECT t1.itemid, MAX(t2.[Type]) AS [Type], ' + 
      STUFF
      (
         (
            SELECT DISTINCT ',MAX(CASE WHEN t1.[language] =  '''+ [language] 
              + ''' THEN t1.[Text] END) AS ' + [Language]
            FROM Texts 
            FOR XML PATH('')
          ),
      1,1,'');
SELECT @query += ' FROM texts t1 JOIN items t2 ON t1.ItemId = t2.ID GROUP BY t1.itemid;';

EXECUTE(@query);