Reputation: 1763
Below query is used to find min price of the product
I update my table @Rates with field Available_Count.
But the result is coming duplicate because of GROUP BY.
How i update this?
SET NOCOUNT ON DECLARE @Products TABLE (product_id VarChar(50),product_name VarChar(50) )
INSERT INTO @Products Values ('1','Pen');
INSERT INTO @Products Values ('2','Pencil');
INSERT INTO @Products Values ('3','ASchool Bag');
INSERT INTO @Products Values ('4','Book');
INSERT INTO @Products Values ('5','Pencil Box');
SET NOCOUNT ON DECLARE @Rates TABLE (product_id VarChar(50),price int, Avail_Count VarChar(50))
INSERT INTO @Rates Values ('1','10','1');
INSERT INTO @Rates Values ('3','5','5');
INSERT INTO @Rates Values ('1','5','6');
INSERT INTO @Rates Values ('4','20','3');
INSERT INTO @Rates Values ('4','15','2');
INSERT INTO @Rates Values ('5','30','1');
;WITH CTE AS (
SELECT
count(*) over() Total_Record,
p.product_id, p.product_name, ISNULL(MIN(r.price), 0) AS MinPrice,
case when ISNULL(MIN(r.price), 0) > 0 then 1 else 0 end as sortOrder,
R.Avail_Count
FROM
@Products p LEFT OUTER JOIN @Rates r
ON
r.product_id = p.product_id
GROUP BY
p.product_id, p.product_name,R.Avail_Count
),ROWNUM as (Select *,ROW_NUMBER() OVER (ORDER BY sortOrder desc, MinPrice asc,Product_name)
AS RowNumber from CTE )
Select * from ROWNUM
Upvotes: 1
Views: 683
Reputation:
I am not sure which avail_count you want to show. You are getting duplicates because you are including avail_count in the GROUP BY and they have different values. Do you want the avail_count value that happens to be on the same row as the min value? If so then:
;WITH x AS
(
SELECT
Total_Record = COUNT(*) OVER(),
rn = ROW_NUMBER() OVER (PARTITION BY p.product_id ORDER BY r.price),
p.product_id,
p.product_name,
MinPrice = COALESCE(r.price, 0),
sortOrder = CASE WHEN COALESCE(r.price, 0) > 0 THEN 1 ELSE 0 END
FROM
@Products AS p
LEFT OUTER JOIN
@Rates AS r
ON r.product_id = p.product_id
)
SELECT
Total_Record,
product_id,
product_name,
MinPrice,
sortOrder,
RowNumber = ROW_NUMBER() OVER (ORDER BY sortOrder DESC, MinPrice, product_name)
FROM x WHERE rn = 1;
If not then you need to show actual desired results rather than just explain that you don't want duplicates.
Upvotes: 1