SQL 嵌套联接显示每个产品的当前价格并使用 MAX()
SQL Nested join showing the current price of each product and using MAX()
目前每种产品的价格是多少?显示产品代码、产品描述、单位及其当前价格。
提示:您将使用 MAX()。这是嵌套连接。
产品TABLE
产品代码
描述
单位
价格历史
有效日期
产品代码
单价
有人可以帮助我改进脚本吗?
这是我的脚本,我正在使用 ibm.cloud
SELECT p.prodCode, p.description, p.unit, MAX(ph.unitPrice) "Current Price"
FROM product p
FULL JOIN priceHist ph
ON p.prodCode = ph.prodCode
GROUP BY p.prodCode, p.description, p.unit
ORDER BY MAX (ph.unitPrice);
我认为不需要完全连接(使用 left join
),您可以使用 where
子句,如下所示:
SELECT p.prodCode, p.description, p.unit, coalesce(ph.unitPrice,p.unitprice) "Current Price"
FROM product p
Left JOIN priceHist ph ON p.prodCode = ph.prodCode
WHERE ph.prodcode is null
or ph.date_col = (select max(phh.date_col) from pricehist phh on phh.prodcode = ph.prodcode)
这将在 table 中为您提供每种产品及其最新价格。
SELECT p.prodCode, p.description, p.unit,
(SELECT unitPrice
FROM priceHist
WHERE prodCode = p.prodCode
ORDER BY effDate DESC
LIMIT 1
) "Current Price"
FROM product p;
在 DB2 中,我会推荐 window 函数:
SELECT p.prodCode, p.description, p.unit, ph.unitPrice as current_price
FROM product p LEFT JOIN
(SELECT ph.*,
ROW_NUMBER() OVER (PARTITION BY prodCode ORDER BY effdate) as seqnum
FROM priceHist ph
) ph
ON ph.prodCode = p.prodCode AND ph.seqnum = 1
ORDER BY ph.unitPrice;
目前每种产品的价格是多少?显示产品代码、产品描述、单位及其当前价格。 提示:您将使用 MAX()。这是嵌套连接。
产品TABLE
产品代码
描述
单位
价格历史
有效日期
产品代码
单价
有人可以帮助我改进脚本吗?
这是我的脚本,我正在使用 ibm.cloud
SELECT p.prodCode, p.description, p.unit, MAX(ph.unitPrice) "Current Price"
FROM product p
FULL JOIN priceHist ph
ON p.prodCode = ph.prodCode
GROUP BY p.prodCode, p.description, p.unit
ORDER BY MAX (ph.unitPrice);
我认为不需要完全连接(使用 left join
),您可以使用 where
子句,如下所示:
SELECT p.prodCode, p.description, p.unit, coalesce(ph.unitPrice,p.unitprice) "Current Price"
FROM product p
Left JOIN priceHist ph ON p.prodCode = ph.prodCode
WHERE ph.prodcode is null
or ph.date_col = (select max(phh.date_col) from pricehist phh on phh.prodcode = ph.prodcode)
这将在 table 中为您提供每种产品及其最新价格。
SELECT p.prodCode, p.description, p.unit,
(SELECT unitPrice
FROM priceHist
WHERE prodCode = p.prodCode
ORDER BY effDate DESC
LIMIT 1
) "Current Price"
FROM product p;
在 DB2 中,我会推荐 window 函数:
SELECT p.prodCode, p.description, p.unit, ph.unitPrice as current_price
FROM product p LEFT JOIN
(SELECT ph.*,
ROW_NUMBER() OVER (PARTITION BY prodCode ORDER BY effdate) as seqnum
FROM priceHist ph
) ph
ON ph.prodCode = p.prodCode AND ph.seqnum = 1
ORDER BY ph.unitPrice;