繁体   English   中英

从子查询发现集中选择记录(postgres)

[英]Selecting records from subquery found set (postgres)

我对2个表(零件,价格)有疑问。 该查询的简化版本为:

SELECT price.* 
FROM price 
INNER JOIN parts ON (price.code = part.code ) 
WHERE price.type = '01' 
ORDER BY date DESC

返回几条记录:

 code        | type     | date                | price      |  file
-------------+----------+------------------------------------------------------
 00065064705 | 01       | 2008-01-07 00:00:00 |  16.400000 | 28SEP2011.zip
 00065064705 | 01       | 2007-02-05 00:00:00 |  15.200000 | 20JUL2011.zip
 54868278900 | 01       | 2006-02-24 00:00:00 |  16.642000 | 28SEP2011.zip

如您所见,代码00065064705列出了00065064705 我只需要maxdate记录(2008-01-07)以及每个唯一代码的代码,类型,日期和价格。 因此,基本上每个唯一代码的最高记录。 这个postgres,所以我不能使用SELECT TOP之类的东西。

我想我应该在主查询中将此作为子查询使用,但我不确定如何使用。 就像是

SELECT * 
FROM price 
JOIN (insert my original query here) AS price2 ON price.code = price2.code

任何帮助将不胜感激。

您可以使用row_number()窗口函数执行此操作。

select *
  from (SELECT price.*,
               row_number() over (partition by price.code order by price.date desc) as rn
          FROM price
         INNER JOIN parts ON (price.code = part.code ) 
         WHERE price.type='01') x
 where rn = 1
 ORDER BY date DESC

(*)注意:我可能不正确地为某些列添加了前缀,因为我不确定哪个表位于哪个表中。 我确定您可以解决该问题。

在Postgres中,您可以使用DISTINCT ON

SELECT DISTINCT ON(code) *
FROM price 
INNER JOIN parts ON price.code = part.code 
WHERE price.type='01' 
ORDER BY code, "date" DESC
select distinct on (code)
    code, p.type, p.date, p.price, p.file
from
    price p
    inner join 
    parts using (code) 
where p.type='01' 
order by code, p.date desc

http://www.postgresql.org/docs/current/static/sql-select.html#SQL-DISTINCT

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM