SQL联合查询按字段分组并投影到展平结果集

时间:2011-12-09 14:09:10

标签: sql tsql

我正在尝试编写一个查询,该查询将从具有不同条件的同一个表中检索记录,并以扁平格式显示结果,如下所示:

期望结果

  

ID,Word,Translation_From_Region_1007,Translation_From_Region_1006

     

1,Word1,Test 1,Test 2

     

2,Word2,测试3,测试4

我的查询的伪代码如下,但我不完全确定如何将结果展平以显示我想要的结果:

SELECT     Words.ID, Words.Word, Translation
FROM         Words  WHERE RegionId=1007
UNION 
SELECT     Words.ID, Words.Word, Translation
FROM         Words WHERE RegionId=1006

Group by Word (as I only want one instance of the word itself with its respective translations flattened.

如果有人能给我任何建议或建议更好的方法,我会非常感激。

4 个答案:

答案 0 :(得分:3)

这个怎么样?

select word, max(Translation1006), max(Translation1007)
from
   (SELECT     
       words.word,
       Translation1006 = 
       CASE region
        when 1006 THEN trans
        else NULL
    END,  
    Translation1007 =
    CASE region
        when 1007 THEN trans
        else NULL
    END
    FROM
       words) as detail
group by word

答案 1 :(得分:2)

这样的事情怎么样?

select A.ID, A.Word, Trans1007 = A.Translation, Trans1006 = B.Translation
    from WORDS A
    left outer join WORDS B on A.ID = B.ID and B.RegionId = 1006
    where A.RegionId = 1007
union
select B.ID, B.Word, Trans1007 = A.Translation, Trans1006 = B.Translation
    from WORDS B
    left outer join WORDS A on B.ID = A.ID and A.RegionId = 1007
    where B.RegionId = 1006

或者你可以像这样进行旋转(如果你想要查询的区域不仅仅是两个,那就更好了)...

select ID, Word, [1006] as T_1006, [1007] as T_1007
    from (select Id, Word, RegionId, Translation from WORD where RegionId in (1006, 1007)) w
    pivot (
        max(Translation)
        for RegionId in([1006], [1007])
        ) as pvt

答案 2 :(得分:2)

如果您使用的是SQL Server,那么您实际上可以平移翻译,在每个翻译条目之间添加逗号。

SELECT Main.ID, Main.Word, Main.Translations 
FROM(SELECT distinct Words2.ID, Words2.Word,
       (SELECT Words1.Translation + ',' AS [text()]
        FROM WORDS Words1
        WHERE Words1.ID = Words2.ID
        AND Words1.RegionId in (1007, 1006)
        ORDER BY Words1.ID
        For XML PATH ('')) [Translations]
FROM WORDS Words2) [Main]

另一个简单的例子可以通过这个堆栈溢出问题找到:

Concatenate many rows into a single text string?

或者,您可以在此处找到许多在Oracle中执行此操作的示例:

http://www.dba-oracle.com/t_display_multiple_column_values_same_rows.htm

答案 3 :(得分:0)

    SELECT distinct Words.ID, Words.Word, Translation
    FROM Words  
    WHERE RegionId=1007 or RegionId=1006