我有这张桌子
(城市,商店ID,商品ID,价格)
我需要返回每个城市,itemID商店ID,以及该商品的最低价格和本身的最低价格(城市,itemID,storeIDmin,minprice)。
有人可以帮助我进行此查询吗?
谢谢!
答案 0 :(得分:1)
您可以使用相关的子查询来解决此问题:
select t.*
from t
where t.price = (select min(t2.price) from t t2 where t2.itemId = t.itemId);
答案 1 :(得分:1)
我通过Join和Subquery解决了这个问题(如果在Oracle DB上工作,也可以使用“ WITH AS”子句):
SELECT table1.city, table1.itemID, table1.storeID as storeIDmin, subquery.min_price
FROM table1
JOIN (select city, itemID, min(price) as min_price from table1
group by city,itemID) AS subquery
ON table1.city = subquery.city
AND table1.itemID = subqueryitemID
AND table1.price =
subquery.min_price
例如结果
+------+---------+--------+-------+
| city | storeID | itemID | price |
+------+---------+--------+-------+
| 1 | 1 | 1 | 70 |
| 1 | 2 | 1 | 60 |
| 2 | 1 | 1 | 100 |
| 2 | 1 | 2 | 90 |
| 2 | 2 | 1 | 88 |
| 3 | 1 | 1 | 70 |
+------+---------+--------+-------+
将得到:
+------+--------+----------+-------+
| city | itemID | storeMin | price |
+------+--------+----------+-------+
| 2 | 1 | 1 | 88 |
| 3 | 1 | 1 | 70 |
| 2 | 2 | 1 | 90 |
| 1 | 1 | 2 | 60 |
+------+--------+----------+-------+