选择Distinct返回多行

时间:2014-12-16 15:19:53

标签: sql sql-server postgresql distinct

我的查询是:

SELECT DISTINCT a.field1, a.field2, a.field3, b.field1, b.field2, a.field4 
FROM table1 a
JOIN table2 b ON b.fielda = a.fieldb 
WHERE a.field1 = 'xxxx'

我运行它并返回三个xxxx行。我需要上面列出的所有信息,第一个字段是不同的。我有正确的语法吗?

3 个答案:

答案 0 :(得分:1)

在Postgres中,您可以使用distinct on

select distinct on (a.field1) a.field1, a.field2, a.field3, b.field1, b.field2, a.field4
from table1 a join
     table2 b
     on b.fielda = a.fieldb
where a.field1 = 'xxxx'
order by a.field1;

在Postgres或SQL Server中,您可以使用row_number()

select ab.*
from (select a.field1, a.field2, a.field3, b.field1, b.field2, a.field4,
             row_number() over (partition by a.field1 order by a.field1) as seqnum
      from table1 a join
           table2 b
           on b.fielda = a.fieldb
      where a.field1 = 'xxxx'
     ) ab
where seqnum = 1;

或者,由于您只需要一行,因此可以使用limit / top

select a.field1, a.field2, a.field3, b.field1, b.field2, a.field4
from table1 a join
     table2 b
     on b.fielda = a.fieldb
where a.field1 = 'xxxx'
limit 1;

在SQL Server中:

select top 1 a.field1, a.field2, a.field3, b.field1, b.field2, a.field4
from table1 a join
     table2 b
     on b.fielda = a.fieldb
where a.field1 = 'xxxx';

答案 1 :(得分:0)

一种选择是使用row_number()

with cte as (
    select distinct a.field1, a.field2, a.field3, b.field1, b.field2, a.field4,
          row_number() over (partition by a.field1 order by a.field1) rn
    from table1 a
        join table2 b on b.fielda = a.fieldb 
    where a.field1 = 'xxxx'
    )
select * 
from cte
where rn = 1

但您需要定义要采用的记录。此订单按field1排序,基本上会随机记录......

答案 2 :(得分:0)

正如您可以从您的评论中读到的,DISTINCT无法为您效劳。它为您提供了不同的。你需要的是一个聚合,以便从三个记录到一个记录。

所以你得到的第一条评论(由sgeddes提供)已经是你需要的答案:“其他专栏应该有什么价值?”。 dbms如何知道?你没有告诉它。

每个字段1一行通常表示GROUP BY字段1。然后对于每个其他字段决定你想看到什么:field2的最大值可能是多少? field3的最小值? field4的平均值?

select a.field1, max(a.field2), min(a.field3), count(b.field1), sum(b.field2), avg(a.field4) 
from table1 a
join table2 b on b.fielda = a.fieldb
where a.field1 = 'xxxx'
group by a.field1;
相关问题