如果我的表格中包含pid, sid
列作为主键,price
和color
。
如何创建一个SQL查询,可以获取pid
({1}}等于color
的每个green
(产品ID)最便宜的价格?
例如我有行:
(1, 1, 10, "green")
(1, 2, 8, "green")
(1, 3, 11, "green")
(2, 1, 7, "green")
(2, 2, 15, "green")
(2, 3, 22, "green")
(3, 1, 10, "red")
(1, 2, 8, "red")
(1, 3, 11, "red")
然后我会收到:(1, 2, 8)->pid=1
和(2, 1, 7)->pid=2
。没有pid=3
,因为它的颜色为红色。
提前致谢。
答案 0 :(得分:1)
SELECT pid, min(Price)
from table
Where Color='green'
group by pid
或者如果你想要整行(并且你的sql平台支持排名)......
select *
from
(
select *, ROW_NUMBER() over (partition by pid order by price) rn
from #t
where color='green'
) v
where rn=1
答案 1 :(得分:0)
试试这个,
SELECT a.*
FROM tableName a
INNER JOIN
(
SELECT pid, min(price) minPrice
FROM tableName b
) c ON a.pid = c.pid AND
a.price = c.minprice
WHERE a.color = 'green'