如果您有少量數據(不是數萬行),則可以執行子查詢。
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')
請問這是爲什麼比GROUP BY好?更快? 這看起來好像不太易讀/簡單,所以我認爲勝利在於表現? – DVK 2010-06-03 01:51:01
如果您使用嵌套子查詢,可以使用GROUP BY做這件事,但這樣做根本不可讀,而且執行得非常糟糕。事實上,你甚至不需要GROUP BY的解決方案 - 你可以使用TOP和DISTINCT。 – 2010-06-03 02:04:22
+1。尼斯CTE解決方案。 – 2010-06-03 05:17:46