2017-09-14 65 views
-2

我試圖找到價格的行號,同時將它們分組在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 
+1

什麼'smt'和'sth'? –

+1

我不明白PriceRank背後的邏輯。向我們展示數據庫架構,示例數據,當前和預期輸出。 \t請閱讀[**如何提問**](http://stackoverflow.com/help/how-to-ask) \t \t這裏是一個偉大的地方[** START **] (http://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/)來了解如何提高您的問題質量並獲得更好的答案。 \t [**如何創建一個最小,完整和可驗證的示例**](http://stackoverflow.com/help/mcve) –

+0

您可以在上面看到示例數據庫和結果表。 PriceRank背後的想法是,我需要找到價格等於1000的訂單,因爲不同的ProductIds – jores

回答

1

這會給你正確的結果:

select * from 
(SELECT ProductId,price,ROW_NUMBER() 
OVER (partition by productid order by productid) AS PriceRank 
FROM products) a 
WHERE price =1000 
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 
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