错误与组由在相关子查询内的查询
我写下面的查询是没有任何错误消息但是我看到的问题与输出返回输出:错误与组由在相关子查询内的查询
select productid, productname, categoryid, unitprice
FROM production.products as PP
where unitprice in (select min(unitprice) as minprice
from production.products as PC
group by categoryid)
order by categoryid
go
结果:
24 Product QOGNU 1 4.50
3 Product IMEHJ 2 10.00
19 Product XKXDO 3 9.20
21 Product VJZZH 3 10.00
33 Product ASTMN 4 2.50
52 Product QSRXF 5 7.00
54 Product QAQRL 6 7.45
74 Product BKAZJ 7 10.00
13 Product POXFU 8 6.00
输出显示categoryid = 3的多行。当我们按categoryid分组时,不应该显示每个categoryid只有一行(一分钟单价)。
我哪里错了? 在此先感谢大家的帮助。
您目前的查询存在的问题是,最低价格的子查询实际上是来自各个类别的最低价格全部的池。但是你真的想限制你的查询到每个类别的最低价格。一种方法是加入你的子查询,按照你想要的方式限制结果集。
SELECT
PP.productid,
PP.productname,
PP.categoryid,
PP.unitprice
FROM production.products AS PP
INNER JOIN
(
SELECT categoryid, MIN(unitprice) AS minprice
FROM production.products
GROUP BY categoryid
) t
ON PP.categoryid = t.categoryid AND
PP.unitprice = t.minprice
ORDER BY categoryid
谢谢大家。现在我知道我出错了。你的回答非常有帮助! –
@NikhilaBakurupanda标记正确吗? –
您的查询没有相关性。你似乎打算:
select productid, productname, categoryid, unitprice
FROM production.products p
where p.unitprice = (select min(p2.unitprice) as minprice
from production.products p2
where p2.categoryid = p.categoryid
)
order by p.categoryid;
一个group by
不相关子查询作。 A where
(好的,有时候也是on
)。
您的具体查询有一个逻辑问题。它得到任何产品,其价格是任何类别的最低价格 - 甚至不是它自己的。
我会写为:
select p.productid, p.productname, p.categoryid, p.unitprice
from (select p.*,
min(p.price) over (partition by p.categoryid) as minprice
from production.products p
) p
where p.price = p.minprice
order by p.categoryid;
注:如果有多个产品都具有相同的最低价格,那么这将返回所有的人。如果你特别想要一个,然后用row_number()
:
select p.productid, p.productname, p.categoryid, p.unitprice
from (select p.*,
row_number() over (partition by p.categoryid order by p.price asc) as seqnum
from production.products p
) p
where seqnum = 1
order by p.categoryid;
你想要得到的最小单位的价格为每个类别?
SELECT * FROM (
SELECT productid, productname, categoryid, unitprice,ROW_NUMBER()OVER(PARTITION BY categoryid ORDER BY unitprice) AS ln
FROM production.products as PP
) AS t WHERE t.ln=1
order by categoryid
您只在子查询中分组。此外,您的'IN'与每个价格相比不是产品类别的价格。选中Tim回答,看看如何使用'JOIN' –