SQL 服务器显示详细信息起始 ID 具有 maxcount 和 on

SQL Server Display details starting ID having maxcount and on

我有 SQL 查询来显示所有产品详细信息。我的产品 table 有 DefectID(表示产品有缺陷),相同的缺陷 ID 是 repeatable 不同 products.I 需要显示以 defectID 开头的产品详细信息,已发生的最大数量然后是下一个最大值等等。

尝试使用 Count()Over()

;with cte as
(
    select Prod_Id,Prod_Desc,..., Count(*) Over(Partition by DefectID) as ct1 from My_Product
}
select * from cte order by ct1 desc
  • 首先计算缺陷数
  • 然后为每个缺陷分配一个id以显示排名
  • 然后加入您的 product table 并订购 defect rank

.

 WITH countDefect as (
      SELECT DefectID, COUNT(defectID) cTotal
      FROM Products 
      GROUP BY DefectID
 ),
 rankDefect as ( 
     SELECT DefectID, row_number() over (order by cTotal DESC) as dRank
     FROM countDefect 
 )
 SELECT Product.*, R.dRank
 FROM Products P 
 INNER JOIN rankDefect  R
    ON P.DefectID = R.DefectID
 ORDER BY R.dRank