在此示例数据库中,有两个表,产品和价格。 目标是找到每种产品的最高价和最低价。
价格表每个产品可以有零行,一行或两行。
create table products(
id int,
name nvarchar(50)
)
create table prices(
productId int,
price int
)
insert into products (id, name) values (33,'bike')
insert into products (id, name) values (44,'car')
insert into products (id, name) values (55,'bus')
insert into prices (productId, price) values (33, 10)
insert into prices (productId, price) values (33, 40)
insert into prices (productId, price) values (44, 300)
sql查询应该导致:
productId highPrice lowPrice
33 40 10
44 300 NULL
55 NULL NULL
答案 0 :(得分:4)
SELECT productId,
MAX(price) AS highPrice,
MIN(price) AS lowPrice
FROM prices
GROUP BY productId
如果您还想要产品名称:
SELECT name,
MAX(price) AS highPrice,
MIN(price) AS lowPrice
FROM products
LEFT OUTER JOIN prices ON ID = ProductID
GROUP BY name
答案 1 :(得分:4)
这适用于MySQL,但它也可能对你有用。
SELECT
products.id as productId
, MIN(price) as highPrice
, MAX(price) as lowPrice
FROM products
LEFT JOIN prices ON products.id=prices.productId
GROUP BY products.id
答案 2 :(得分:1)
这为您提供了您正在寻找的表(我注意到其他答案没有),在SQL Server 2005中
select P.ID as ProductID,
nullif(sum(case when idx=1 then price else 0 end), 0) as highPrice,
nullif(sum(case when idx=2 then price else 0 end), 0) as lowPrice from
(
select productid, price, row_number() over(partition by productID order by price desc) as idx from prices
) T
right join products P on T.productID = P.ID
group by P.ID