gpt4 book ai didi

sql - Postgres : GROUP BY several column

转载 作者:行者123 更新时间:2023-11-29 11:35:21 27 4
gpt4 key购买 nike

在这个例子中我有两个表。

(示例列名)

首先是产品

product_id | product_text

第二张表是价格。

price_productid | price_datestart | price_price

假设我对同一产品有多个日期开始。我怎样才能得到实际价格?

如果我在 Postgres 中使用 GROUP BY,对于所有选定的列,同一产品可能会出现 2 行。因为列 price_datestart 不同。

示例:

product_id : 1
product_text : "Apple Iphone"


price_productid : 1
price_datestart :"2013-10-01"
price_price :"99"


price_productid : 1
price_datestart :"2013-12-01"
price_price :"75"

如果我尝试这样做:

SELECT price_productid,price_datestart,price_price,product_text,product_id
WHERE price_datestart > now()
GROUP BY price_productid,price_datestart,price_price,product_text,product_id
ORDER BY price_datestart ASC

它会给我一个结果,但是有两行,我需要一个。

最佳答案

使用 distinct on 语法。如果您想要当前价格:

select distinct on (p.productid)
p.productid, pr.product_text, p.price, p.datestart
from Price as p
left outer join Product as pr on pr.productid = p.productid
where p.datestart <= now()
order by p.productid, p.datestart desc

sql fiddle demo

关于sql - Postgres : GROUP BY several column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18891131/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com