我有一组记录,我想根据组中的项目数对这些记录进行排序。
我想以这样的方式安排记录,即最大项目数的产品位于顶部,即所需订单是 - Product_ID 3(包含6个项目),然后是Product_ID 1(包含5个项目),最后一个将是Product_ID 2(包含3个项目)。
以下查询返回具有相同Product_ID的项目的计数,但是,我还要安排Item_Name,Item_Description和Item_Number。
Select Product_ID, Count(*) from Product group by Product_ID order by Count(*) DESC
我已经尝试了另外一个查询,但是我知道我错了,它没有给出预期的结果,我想不出可能的解决方案:
Select Product_ID, Item_Name, Item_Description, Item_Number from Product
group by Product_ID,item_name,item_description,item_number
order by COUNT(product_ID)
先谢谢你的帮助!!
答案 0 :(得分:4)
Select Product_ID, Item_Name, Item_Description, Item_Number
from Product
order by COUNT(1) over (partition by Product_ID) desc
答案 1 :(得分:1)
我假设您只想按ID进行分组,但是您想要列出所有其他字段,如果您只想按以下顺序排序,则根本不需要分组:
SELECT product_id,
item_name,
item_description,
item_number
FROM product p1
ORDER BY (SELECT Count(product_id)
FROM product p2
WHERE p1.product_id = p2.product_id) DESC
答案 2 :(得分:0)
尝试使用别名:
Select Product_ID, Count(*) AS num_products from Product group by Product_ID order by num_products DESC;