0

如果我有一个以列pid, sid作为主键的表,price并且color.

如何创建一个 SQL 查询,该查询可以获取每个pid(产品 ID)color等于的最便宜的价格green

例如我有行:

(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,因为它的颜色是红色的。

提前致谢。

4

2 回答 2

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
于 2012-08-21T08:41:11.110 回答
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'
于 2012-08-21T08:54:07.340 回答