如何避免来自群组的重复记录?

时间:2012-01-24 23:58:25

标签: sql-server tsql sql-server-2005 group-by

以下查询用于查找产品的最低价格

我使用字段Available_Count更新我的表@Rates。

但结果因为GROUP BY而重复。

我如何更新?

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 

1 个答案:

答案 0 :(得分:1)

我不确定您要显示哪个avail_count。您正在获得重复项,因为您在GROUP BY中包含avail_count并且它们具有不同的值。您是否希望avail_count值恰好与最小值位于同一行?如果是,那么:

;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;

如果没有,那么你需要显示实际的预期结果,而不是仅仅解释你不想要重复。