如何在PostgreSQL中比较两行相同的条目?

时间:2014-02-19 05:24:31

标签: sql postgresql comparison aggregate-functions

以下是我对Postgres数据库运行的查询。

select distinct(col1),col2,col3,col4 
    from tableNot 
    where col5 = 100 and col6 = '78' 
    order by col4 DESC  limit 100;

以下是我回到控制台的输出 -

col1            col2       col3      col4 

entry.one       1.2.3       18       subject
entry.one       1.2.8       18       newSubject
entry.two       3.4.9       20       lifePerfect
entry.two       3.4.5       17       helloPartner
  • 现在,如果您看到我的上述输出,entry.oneentry.two将会出现两次,那么我会比较col2的{​​{1}}值,以较高者为准,我将保留该值行。因此,对于entry.one,我会将entry.one1.2.3进行比较,1.2.8的{​​{1}}更高,因此我只会将此行保留为1.2.8
  • entry.one类似,我会将entry.oneentry.two进行比较,3.4.9的{​​{1}}更高,因此我会将此行仅保留为{{1} }}。

以下是我希望在控制台上看到的输出 -

3.4.5

这可以在SQL中做吗?

P.S任何小提琴的例子都很棒。

3 个答案:

答案 0 :(得分:2)

您可能正在寻找distinct on,这是distinct运营商的Postgres特定扩展。

select distinct on (col1)  col1, col2, col3, col4 
from tableNot 
where col5 = 100 
  and col6 = '78' 
order by col1, col4 DESC  
limit 100;

http://sqlfiddle.com/#!15/04698/1


请注意,distinct 不是一项功能。 select distinct (col1), col2, col3select distinct col1, col2, col3完全相同。

(标准SQL)distinct运算符始终在选择列表的所有列上运行,而不仅仅是一个。

select distinct (col1), col2select distinct col1, col2之间的差异与select (col1), col2select col1, col2之间的差异相同。

答案 1 :(得分:1)

尝试此查询:

SELECT * FROM
(select distinct(col1),col2,col3,col4 from tableNot 
where col5 = 100 and col6 = '78' order by col4 DESC  limit 100)t1
WHERE t1.col2 = (SELECT MAX(t2.col2) FROM (select distinct(col1),col2,col3,col4 
from tableNot 
where col5 = 100 and col6 = '78' order by col4 DESC  limit 100)t2 
WHERE t1.col1 = t2.col1 group by t2.col1)

SQL Fiddle

答案 2 :(得分:0)

您可以尝试其他简单查询:

SELECT DISTINCT t1.col1, t1.col2, t1.col3, t1.col4 
FROM tableNot t1 
INNER JOIN (SELECT MAX(col2) col2 
FROM tableNot GROUP BY col1) t2  ON t1.col2=t2.col2
WHERE col5 = 100 AND col6 = '78' ORDER BY col4 DESC  LIMIT 100;