我正在使用PostgreSQL。我有三张桌子:
Items(itemid, description, size, color)
Inventory(storeid, itemid, qty)
Stores(storeid, city, managerid)
我的任务是找到纳什维尔商店中库存中最常见的商品尺寸。这是预期的解决方案:
size
------
medium
small
我在这里:
select size, count(size)
from items
join inventory using (itemid)
where storeid in (select storeid from stores where city = 'Nashville')
group by size;
哪个收益
size | count
--------+-------
large | 3
medium | 4
small | 4
(3 rows)
我知道我很亲密,但我不确定如何打印中小型。我可以硬编码上面的内容并添加"有计数(大小)= 4,"但只会匹配输出。我想制作一个临时表并将其加入到上面的查询中以允许我引用最大值(计数),但我还没有找到一种我能理解的方法。我不是盲目复制,我想学习。谢谢。
答案 0 :(得分:0)
with s as (
select size, count(size) as size_count
from
items
inner join
inventory using (itemid)
inner join
stores using (storeid)
where city = 'Nashville'
group by size
)
select size, size_count
from s
where size_count = (select max(size_count) from s)