SQL查询某城市某商品最低价的店铺
SQL query for the store with the minimum price of an item in the city
我有这个table
(城市,storeID,itemID,价格)
我需要为每个城市 return itemID storeID 以及商品的最低价格和最低价格本身 ( city,itemID,storeIDmin,minprice)。
有人可以帮我解决这个问题吗?
谢谢!
您可以使用相关子查询来解决这个问题:
select t.*
from t
where t.price = (select min(t2.price) from t t2 where t2.itemId = t.itemId);
我用 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 |
+------+--------+----------+-------+
我有这个table
(城市,storeID,itemID,价格)
我需要为每个城市 return itemID storeID 以及商品的最低价格和最低价格本身 ( city,itemID,storeIDmin,minprice)。
有人可以帮我解决这个问题吗?
谢谢!
您可以使用相关子查询来解决这个问题:
select t.*
from t
where t.price = (select min(t2.price) from t t2 where t2.itemId = t.itemId);
我用 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 |
+------+--------+----------+-------+