SQL DISTINCT值问题

时间:2010-06-03 01:14:14

标签: sql group-by distinct

如何在查询中过滤结果?示例

我有5条记录

  

约翰史密斯,苹果
  简,DOE,苹果
  弗雷德·詹姆斯,苹果
  比尔·埃文斯,橙色
  威尔玛,琼斯,葡萄

现在我想要一个查询,它会带回DISTINCT FRUIT的3条记录,但是......这里是棘手的部分,我仍然想要名字,姓氏的列。 PS我不在乎它回想起你的哪一个,但我需要它只返回3(或者有多少DISTINCT水果。

退货将是

  

约翰史密斯,苹果
  比尔·埃文斯,橙色
  Willma,琼斯,葡萄

提前谢谢,我一整天都在敲打着。

4 个答案:

答案 0 :(得分:3)

奇怪的是,最好的解决方案不涉及GROUP BY。

WITH DistinctFruit AS (
    SELECT 
        ROW_NUMBER() OVER (PARTITION BY Fruit ORDER BY LastName) AS FruitNo, 
        LastName,  
        FirstName, 
        Fruit 
    FROM table)
SELECT FirstName, LastName, Fruit
FROM  DistinctFruit
WHERE FruitNo = 1;

答案 1 :(得分:0)

如果您有少量数据(不是数万行),您可以进行子查询。

select distinct t1.fruit as Fruit, 
    (select top 1 t2.lastname 
    from t1 as t2
    where t1.fruit = t2.fruit
    order by t2.lastname) as LastName,
    (select top 1 t2.firstname 
    from t1 as t2
    where t1.fruit = t2.fruit
    order by t2.lastname, t2.firstname) as FirstName
from t1

请注意,FirstName列的排序方式与LastName列相同。这将为您提供匹配的姓氏和正确的名字。

这是我的测试数据:

create table t1
(firstname varchar(20),
lastname varchar(20),
fruit varchar(20))


insert into t1
values ('John','Smith','apple')
insert into t1
values ('Jane','Doe','apple')
insert into t1
values ('Fred','James','apple')
insert into t1
values ('Bill','evans','orange')
insert into t1
values ('Willma','Jones','grape')

答案 2 :(得分:0)

只是另一种解决方案

    select distinct x.*,fruit from t1 
    cross apply 
    (select top 1 firstname, lastname from t1 t2 where t1.fruit=t2.fruit) x

答案 3 :(得分:0)

SELECT DISTINCT x.*,fruit FROM peopleFruit pf 
CROSS APPLY  
(SELECT TOP 1 firstname, lastname FROM peopleFruit pf1 WHERE pf.fruit=pf1.fruit) x