如何在不使用聚合函数的情况下使用group by

时间:2017-09-14 02:52:17

标签: sql sql-server

我正在尝试查找价格的行号,同时将它们与ProductId进行分组。对于ProductId = 1,价格等级(价格= 1000)应为smt。对于productId=3,价格等级(= 1000)应为......

  • 如何在同一张表中找到不同productId的价格行数?

  • 如何在不使用Row_number聚合的情况下使用组来实现此目的。

    ProductId   Price
    -----------------
       1         2000
       1         1600
       1         1000
       2         2200
       2         1000
       2         3250
       3         1000
       3         2500
       3         1750
    

所以结果应该是

ProductId   Price   PriceRank
------------------------------
    1       1000       3
    2       1000       2
    3       1000       1

这是我的代码:

SELECT 
    ProductId,
    ROW_NUMBER() OVER (ORDER BY price ASC) AS PriceRank
FROM 
    product
WHERE 
    price = 1000
GROUP BY 
    ProductId

3 个答案:

答案 0 :(得分:1)

这会给你正确的结果:

select * from 
(SELECT ProductId,price,ROW_NUMBER()
OVER (partition by productid order by productid ) AS PriceRank
FROM products) a
WHERE price =1000

答案 1 :(得分:0)

不确定这是否是最好的方法..但它肯定是一种方法来做到这一点

    ;WITH mycte AS (
SELECT
 1 as  ProductId  ,      2000 as  Price
 UNION ALL  SELECT
1 ,        1600
 UNION ALL  SELECT
1 ,        1000
 UNION ALL  SELECT
2 ,        2200
 UNION ALL  SELECT
2 ,        1000
 UNION ALL  SELECT
2 ,        3250
 UNION ALL  SELECT
3 ,        1000
 UNION ALL  SELECT
3  ,       2500
 UNION ALL  SELECT
3 ,        1750
)
,my_rank as (
Select 
ProductId
, Price
,ROW_NUMBER() OVER (ORDER BY (SELECT 1)) rownumber
from mycte

)
,ranking AS (
SELECT 
ProductId
, Price
, rownumber
, ROW_NUMBER() OVER (PARTITION BY ProductId ORDER BY rownumber) pricerank

FROM my_rank
)
SELECT 
ProductId
, Price
,pricerank 

FROM ranking

WHERE Price = 1000

答案 2 :(得分:0)

试试这个:

declare @result table(ProductID smallint, Price int, PriceRank smallint)
declare @product table(ProductID smallint, Price int) --replicate your table data
declare @id smallint
--feed table with your data
insert into @product
select ProductId, Price from product

while(exists(select * from @product))
begin
    select top 1 @id = ProductId from @product
    insert into @result
    SELECT 
        ProductId, price,
        ROW_NUMBER() OVER (ORDER BY ProductID) as CountPerGroup
    FROM @product
    WHERE ProductID = @id
    delete from @product where ProductID = @id
end

select * from @result where Price = 1000