SQL Server显示启动ID为maxcount和on的详细信息

时间:2015-10-06 05:23:14

标签: sql sql-server displaytag

我有SQL查询来显示所有产品详细信息。我的产品表有DefectID(表示产品有缺陷),同样的缺陷ID对于不同的产品是可重复的。我需要显示产品详细信息,从最新发生的最大数量的缺陷ID开始,然后是下一个最大值等等。

2 个答案:

答案 0 :(得分:1)

尝试使用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

答案 1 :(得分:1)

  • 首先计算缺陷计数
  • 然后为每个缺陷分配一个id来显示等级
  • 然后返回您的product表并订购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