SQL& SQL Server - 非规范化表,不同和按复杂查询排序

时间:2015-01-30 15:19:39

标签: sql sql-server select sql-order-by distinct

我最近一直在这里工作,我无法解决这个问题。我有下表:

ID      Language  Text
----    --------  --------    
1       spanish   Hola
1       english   Hello
2       spanish   Chau
2       english   Goodbye
2       french    Au revoir
3       english   Thank you

我需要获得每个ID一次和西班牙语的文本,但如果没有西班牙语的任何文本我应该得到英语,依此类推。

因此,如果我运行此查询,我应该得到:

ID      Language  Text
----    --------  --------    
1       spanish   Hola
2       spanish   Chau
3       english   Thank you

我无法使用

Select ID, Language, Text From table Where Language = 'spanish'

因为在没有西班牙语集的情况下我不会检索该ID,我需要每个ID一个记录。我可能会使用这样的东西:

select Distinct(Id), Text from table 
order by FIELD(Language, 'Spanish', 'English', 'French', 'Italian')

但它没有用。我明白了:

'FIELD' is not a recognized built-in function name.

有人可以帮助我吗?

非常感谢你们!

3 个答案:

答案 0 :(得分:2)

对于此类优先级,您可以使用row_number()

Select t.*
From (select t.*,
             row_number() over (partition by id
                                order by (case when Language = 'Spanish' then 1
                                               when Language = 'English' then 2
                                               else 3
                                          end)
                               ) as seqnum
      from table t
     ) t
where seqnum = 1;

答案 1 :(得分:1)

这是另一种选择:

SELECT i.ID, w.Text
FROM (
   SELECT ID  
   FROM Words
   GROUP BY ID) i(ID)
CROSS APPLY (
   SELECT TOP 1 [Text]
   FROM Words
   WHERE ID = i.ID AND [Language] IN ('spanish', 'english')
   ORDER BY (CASE [Language] WHEN 'spanish' THEN 1                                 
                             ELSE 2
             END)
) w([Text])

对于Words表中包含的每个ID,我们执行CROSS APPLY来查找满足OP设置标准的匹配Text

答案 2 :(得分:0)

select COALESCE(SP.id, EN.id, FR.id) as id,
       COALESCE(SP.Language, EN.Language, FR.Language) as Language, 
       COALESCE(SP.text, EN.text, FR.text) as text 
from (select disctinct id from table) as IDs
left join (select id, Language, text from table where Language = 'spanish') as SP on IDs.id = SP.id
left join (select id, Language, text from table where Language = 'english') as EN on IDs.id = EN.id
left join (select id, Language, text from table where Language = 'french') as FR on IDs.id = FR.id
where COALESCE(SP.id, EN.id, FR.id) is not null -- avoids null results for other languages (if there are)

此解决方案(或COALESCE的等效替代品)适用于我所知道的任何SQL变体