我有3张桌子都需要互动。他们是自行车库存。他们是自行车商店,商店库存和自行车模型。我想在每个店铺库存中找到最便宜的自行车。下面的代码给出了我期望的正确结果,但我也希望显示自行车名称。
SELECT
BS.BIKESHOPNAME, MIN(BM.PRICE)
FROM
BIKESHOP BS, BIKEMODEL BM, SHOPINVENTORY SI
WHERE
SI.BIKESHOPID = BS.BIKESHOPID
AND SI.BIKEID = BM.BIKEID
GROUP BY
BS.BIKESHOPNAME;
如果我将select语句更改为:
SELECT BS.BIKESHOPNAME, BM.NAME, MIN(BM.PRICE)
我得到的结果太多了。我是否必须检查名称是否与自行车型号匹配?
答案 0 :(得分:1)
可能尝试一下吗?这是一个如何使用加入的示例
SELECT BS.BIKESHOPNAME, MIN(BM.PRICE), BM.NAME
FROM
BIKESHOP AS BS
INNER JOIN
SHOPINVENTORY AS SI
ON SI.BIKESHOPID = BS.BIKESHOPID
INNER JOIN
BIKEMODEL AS BM
ON BM.BIKEID = SI.BIKEID
GROUP BY BS.BIKESHOPNAME, BM.NAME;
答案 1 :(得分:1)
我认为这可以解决您的问题:
SELECT DISTINCT
BS.BIKESHOPNAME,
FIRST_VALUE(BM.NAME) OVER (PARTITION BY BS.BIKESHOPNAME ORDER BY BM.PRICE ASC),
FIRST_VALUE(BM.PRICE) OVER (PARTITION BY BS.BIKESHOPNAME ORDER BY BM.PRICE ASC)
FROM BIKESHOP BS, BIKEMODEL BM, SHOPINVENTORY SI
WHERE SI.BIKESHOPID = BS.BIKESHOPID AND SI.BIKEID = BM.BIKEID
我不确定这是最好的解决方案,但我认为它会做到。它也可以使用子查询来解决,但我认为这个更好。
的更新:强>
你可以使用这样的子查询:
SELECT
BS.BIKESHOPNAME
(SELECT TOP 1 BM.NAME FROM BIKEMODEL BM, SHOPINVENTORY SII WHERE SII.BIKEID = BM.BIKEID AND SI.BIKESHOPID = BS.BIKESHOPID ORDER BY BM.PRICE ASC) BIKENAME,
(SELECT TOP 1 BM.PRICE FROM BIKEMODEL BM, SHOPINVENTORY SII WHERE SII.BIKEID = BM.BIKEID AND SI.BIKESHOPID = BS.BIKESHOPID ORDER BY BM.PRICE ASC) PRICE
FROM
BIKESHOP BS
答案 2 :(得分:-2)
分组依据仅适用于bikeshopname。包括
按bs.bikeshopname,bm.name
分组
在SQL查询结束时。这应该有用。