以下是数据样本
UnitID ITEM_Num Price
13446 71079 45.57
13447 71079 45.57
13448 71079 52.50
13449 71079 45.57
13450 71079 36.22
实际数据集大约有100个唯一的UnitID和700个唯一的Item_Num值。我正在尝试确定每个Item_Num的最常见价格,然后选择与该标准不同的任何记录超过指定的百分比。
理想情况下,我们会为每件商品设定标准价格值,但我们不会。找到最常见价值的最佳方法是什么。还有一个功能可能能够快速排名物品,其中变化最多的是价格。
这是SQL Server 2012.
答案 0 :(得分:0)
您可以使用GROUP BY语句:
SELECT Price, count(*) FROM my_table GROUP BY Price ORDER BY Price ASC
希望这有帮助!
答案 1 :(得分:0)
以下查询应该在SQL Server中有效。它应该以比最常见价格低10%或更高的价格回馈每个ITEM_Num。
;WITH cte AS (
SELECT
RANK() OVER (PARTITION BY ITEM_Num ORDER BY COUNT(1) DESC) AS 'Rank'
, ITEM_Num
, Price
FROM Units
GROUP BY ITEM_Num, Price
)
SELECT u1.UnitID
, u1.ITEM_Num
, u1.Price
, u2.Price AS 'most common price'
FROM Units u1
INNER JOIN cte AS u2
ON u2.ITEM_Num = u1.ITEM_Num
AND u2.Rank = 1
WHERE ABS(u1.Price - u2.Price) >= (u2.Price * 0.1);
编辑:我写的查询不知道你的DBMS,使用SQL Server的排名功能可能更有效。
答案 2 :(得分:0)
Create table #t(
UnitID int,
Item_Num int,
Price money
)
Insert into #t(Unitid, Item_Num, Price)
values(13446, 71079, 45.57 ),
(13447, 71079, 45.57),
(13448, 71079, 52.50),
(13449, 71079, 45.57),
(13450, 71079, 36.22)
;with cte as (
Select
Unitid, Item_Num, Price,
Row_Number() over ( partition by item_num order by price) rownum
from #t
)
Select
u.UnitID,
u.Item_Num,
u.Price,
U1.price as CommonPrice,
u.RowNum,
U.Price*0.1,
(u.price +(u.price*0.1)) as NewPrice
from cte as U
inner join #t u1 on u.item_num =u1.item_num
where u.rownum =1