如何在SQL中选择具有特定列数的表中的所有列?

时间:2015-05-21 07:50:00

标签: sql sql-server

假设我有这些专栏:

  1. Form_ID
  2. PRODUCT_ID
  3. 日期
  4. 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
    

    有什么想法和帮助吗?谢谢。

2 个答案:

答案 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

MSDN:https://msdn.microsoft.com/en-us/library/ms189461.aspx

答案 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