假设我有这些专栏:
P.S:每个Form_ID可以有多个Product_ID,我希望按照Product_ID的出现次数排序所有数据。我尝试了一些查询,
SELECT * , COUNT(Product_ID) AS indicator
from my_database.inv_table
GROUP BY (Product_ID)
ORDER BY indicator DESC
有什么想法和帮助吗?谢谢。
答案 0 :(得分:2)
您可以使用Count(*) Over (Partition by Product_ID)
:
SELECT Form_ID, Product_ID, Date,
Indicator = Count(*) Over (Partition by Product_ID)
FROM my_database.inv_table
ORDER BY Indicator DESC
如果您不想要,则不需要选择Indicator
- 列,您也可以Count(*) Over (Partition by Product_ID)
使用ORDER BY
。
答案 1 :(得分:1)
使用相关的子查询进行计数:
SELECT t1.*, (select COUNT(*) from my_database.inv_table t2
where t1.Form_ID = t2.Form_ID) AS indicator
from my_database.inv_table t1
ORDER BY indicator DESC