I have SQL Query to display all product details. My product table has DefectID(which says defect on the product), and the same defect ID is repeatable for different products.I need to display product details starting with defectID that has occurred maximum count and then next maximum and so on.
Asked
Active
Viewed 46 times
-3
-
Can you show your query ? , and what is your desired result ? – japzdivino Oct 06 '15 at 05:25
-
At least provide some sample data and expected output – Ullas Oct 06 '15 at 05:26
-
post some sample data and required output – mohan111 Oct 06 '15 at 05:27
2 Answers
1
try using Count()
and 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

A_Sk
- 4,532
- 3
- 27
- 51
-
My two year ago self should be a shame, your answer is much better – Juan Carlos Oropeza Jul 25 '17 at 13:34
1
- First calculate defects counts
- Then assign an id to each defect to show rank
- Then join back to your
product
table and order fordefect 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

Juan Carlos Oropeza
- 47,252
- 12
- 78
- 118