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