Tsql 在sql中查找高价格和低价格

Tsql 在sql中查找高价格和低价格,tsql,Tsql,在这个示例数据库中有两个表:产品和价格。 目标是找到每种产品的最高和最低价格 每个产品的价格表可以有零行、一行或两行 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 (i

在这个示例数据库中有两个表:产品和价格。 目标是找到每种产品的最高和最低价格

每个产品的价格表可以有零行、一行或两行

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
如果您希望产品名称也在其中:

SELECT name,
        MAX(price) AS highPrice,
        MIN(price) AS lowPrice
FROM products
    LEFT OUTER JOIN prices ON ID = ProductID
GROUP BY name
如果您希望产品名称也在其中:

SELECT name,
        MAX(price) AS highPrice,
        MIN(price) AS lowPrice
FROM products
    LEFT OUTER JOIN prices ON ID = ProductID
GROUP BY name

这是针对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

这是针对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

这将为您提供在SQLServer2005中查找的表(我注意到其他答案没有)

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

这将为您提供在SQLServer2005中查找的表(我注意到其他答案没有)

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

但这并没有给用户提供他所想要的结果表。我们确定他写的东西有错吗?我怀疑Simdendsjo有错。我只是展示了如何使用MAX和MIN内置函数来实现这一点。如果您运行我的第二个查询并将“name”替换为“id”,您将从问题中得到完全相同的结果集。男孩,为什么我没有看到这个简单的解决方案。如果您查看所需结果集的第二行,它将“highPrice”显示为300,“lowPrice”显示为NULL。你的代码不会这样做。Rasmus是否真的想要结果集是一个单独的问题(可能他不想要)@Yellowfog,啊啊啊啊,我知道你现在在说什么,但这并没有给用户他所想要的结果表。我们确定他写的东西有错吗?我怀疑Simdendsjo有错。我只是展示了如何使用MAX和MIN内置函数来实现这一点。如果您运行我的第二个查询并将“name”替换为“id”,您将从问题中得到完全相同的结果集。男孩,为什么我没有看到这个简单的解决方案。如果您查看所需结果集的第二行,它将“highPrice”显示为300,“lowPrice”显示为NULL。你的代码不会这样做。Rasmus是否真的想要结果集是一个单独的问题(可能他不想要)@Yellowfog,啊啊啊啊啊,我明白你现在在说什么了谢谢,这正是我为汉克斯寻找的结果,这正是我所寻找的结果