如何在SQl Server 2008中选择distinct,但仅限于多个中的一个字段?

时间:2010-04-27 11:48:28

标签: sql-server

我有一个问题:

SELECT Content.content_name, Language2.Name, Language2.language_id, 
Content.id, Content.content_description, 
FROM Language AS Language2 
LEFT JOIN contents AS Content ON (Language2.language_id = Content.language_id) 

如何仅选择不同的content_name?

3 个答案:

答案 0 :(得分:21)

你这样做:

SELECT DISTINCT Content.content_name
FROM Language AS Language2 
LEFT JOIN contents AS Content ON (Language2.language_id = Content.language_id)

那为什么这不能回答你的问题?

让我们考虑以下数据(仅前两列):

content_name      Name
 XXXXX            1234
 XXXXX            5678

SELECT DISTINCT意味着你只需要一行,但你想要什么名字?

您需要做的是重写代码以使用GROUP BY并为其他列选择适当的聚合函数:

SELECT
    Content.content_name,
    MIN(Language2.Name) AS Name,
    MIN(Language2.language_id) AS language_id, 
    MIN(Content.id) AS id,
    MIN(Content.content_description) AS content_description, 
FROM
    Language AS Language2 
    LEFT JOIN contents AS Content
        ON (Language2.language_id = Content.language_id) 
GROUP BY
    Content.content_name

现在,这可能不会产生你想要的东西,但有一件事是肯定的,你不能欺骗数据库引擎只是“选择其中一行返回,我不关心哪一行。” / p>

答案 1 :(得分:5)

WITH    q AS
        (
        SELECT  Content.content_name, Language2.Name, Language2.language_id, Content.id, Content.content_description, ROW_NUMBER() OVER (PARTITION BY content_name ORDER BY language_id) AS rn
        FROM    Language Language2
        LEFT JOIN
                Contents AS Content
        ON      Language2.language_id = Content.language_id
        )
SELECT  *
FROM    q
WHERE   rn = 1

答案 2 :(得分:1)

你的意思是跟随

SELECT Content.content_name, 
FROM Language AS Language2 
LEFT JOIN contents AS Content ON (Language2.language_id = Content.language_id)
Group by Content.content_name