Sql 如何在不使用聚合函数的情况下使用group by
我试图找到价格的行号,同时根据它们的Sql 如何在不使用聚合函数的情况下使用group by,sql,sql-server,Sql,Sql Server,我试图找到价格的行号,同时根据它们的ProductId对它们进行分组。对于ProductId=1,价格等级(其中价格=1000)应为smt。对于productId=3,价格等级(=1000)应为某物 如何在同一个表中找到不同productId的价格行号 如何使用group by来实现这一点,而无需对行数进行聚合 ProductId Price ----------------- 1 2000 1 1600 1 1000
ProductId
对它们进行分组。对于ProductId=1
,价格等级(其中价格=1000)应为smt。对于productId=3
,价格等级(=1000)应为某物
- 如何在同一个表中找到不同
的价格行号productId
- 如何使用group by来实现这一点,而无需对
行数进行聚合
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
不确定这是不是最好的方法。。但这肯定是一种方法
;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
试试这个:
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
这将为您提供正确的结果:
select * from
(SELECT ProductId,price,ROW_NUMBER()
OVER (partition by productid order by productid ) AS PriceRank
FROM products) a
WHERE price =1000
什么是smt和sth?我不明白PriceRank背后的逻辑。向我们显示数据库模式、示例数据、当前和预期输出。请阅读,这里是学习如何提高问题质量和获得更好答案的好地方。您可以看到上面的示例数据库和结果表。PriceRank背后的思想是,我需要找到不同产品的价格顺序,即等于1000。您的结果表没有指定如何获得该结果。你需要说明你是如何得到订单的。数据集没有任何内在顺序,因此除非您使用orderby,否则无法保证顺序。