SQL 查询仅显示最少行数
SQL query display min count rows only
我试图只显示属于具有最小类别总数的类别的汽车的成本值
这是我正在尝试使用的查询:
select model, VIN,cost
from stock
期望的输出:
Model - VIN - Cost
STI XXXXXXXXXXXX ,000
我知道 having 运算符可用于计算每种汽车的最小类别总数:
having count(distinct category)=(select min(count(category))
from stock group by category)
但我不确定如何实现这样的运算符
如果我没理解错的话,这个查询比看起来要复杂一些。使用子查询获取每个类别的计数,使用 window 函数获取最小计数。然后将其连接回原始数据:
select s.model, s.VIN, s.cost
from stock s join
(select category, count(*) as cnt, min(count(*)) over () as mincnt
from stock s
group by category
) c
on s.category = c.category and cnt = mincnt
with cnt_stock as
(
select count(*) over (partition by category) cat_cnt
, model
, category
from stock
)
select *
from cnt_stock
where cat_cnt =
(
select min(cat_cnt)
from cnt_stock
)
我试图只显示属于具有最小类别总数的类别的汽车的成本值
这是我正在尝试使用的查询:
select model, VIN,cost
from stock
期望的输出:
Model - VIN - Cost
STI XXXXXXXXXXXX ,000
我知道 having 运算符可用于计算每种汽车的最小类别总数:
having count(distinct category)=(select min(count(category))
from stock group by category)
但我不确定如何实现这样的运算符
如果我没理解错的话,这个查询比看起来要复杂一些。使用子查询获取每个类别的计数,使用 window 函数获取最小计数。然后将其连接回原始数据:
select s.model, s.VIN, s.cost
from stock s join
(select category, count(*) as cnt, min(count(*)) over () as mincnt
from stock s
group by category
) c
on s.category = c.category and cnt = mincnt
with cnt_stock as
(
select count(*) over (partition by category) cat_cnt
, model
, category
from stock
)
select *
from cnt_stock
where cat_cnt =
(
select min(cat_cnt)
from cnt_stock
)