我需要更新按价格排序的表格并重新分配订购的价格。 价格和价值按idcategory分组。这是一个例子:
| ID | idcategory | price | value | | 1 | 1 | 10 | 3 | | 2 | 1 | 12 | 30 | | 3 | 1 | 43 | 9 | | 4 | 1 | 32 | 23 | | 5 | 2 | 38 | 13 | | 6 | 2 | 8 | 26 | | 7 | 2 | 3 | 34 | | 8 | 2 | 10 | 12 | . .. .. .. .. .. .. ... ... .. .. .. ..
我需要通过idcategory重新排序表分组,将有序值重新分配给订购价格,如下所示:
| ID | idcategory | price | value | | 1 | 1 | 10 | 3 | | 2 | 1 | 12 | 9 | | 3 | 1 | 32 | 23 | | 4 | 1 | 43 | 30 | | 5 | 2 | 3 | 12 | | 6 | 2 | 8 | 13 | | 7 | 2 | 10 | 26 | | 8 | 2 | 38 | 34 | .. .. .. .. .. .. .. .. .. ... ..
数据库是postgres 9.2。
任何想法都将受到赞赏。
谢谢你,新年快乐!!!
这是基于GarethD建议的更新工作解决方案:
WITH OrderedValues AS ( SELECT Value, Price, idcategory, ROW_NUMBER() OVER(PARTITION BY idcategory ORDER BY Value) AS ValueNum, ROW_NUMBER() OVER(PARTITION BY idcategory ORDER BY Price) AS PriceNum FROM T ), OrderedIDs AS ( SELECT ID, idcategory, ROW_NUMBER() OVER(PARTITION BY idcategory ORDER BY ID) AS RowNum FROM T ), NewValues AS ( SELECT i.ID, v.Value, p.Price FROM OrderedIDs i INNER JOIN OrderedValues v ON i.RowNum = v.ValueNum AND i.idcategory = v.idcategory INNER JOIN OrderedValues p ON i.RowNum = p.PriceNum AND i.idcategory = p.idcategory ) UPDATE T SET Price = v.Price, Value = v.Value FROM NewValues v WHERE v.ID = T.ID; SELECT * FROM T;
答案 0 :(得分:1)
首先需要对您的ID(OrderedID)和价格/价值组合(OrderedValues)进行排名。然后你可以匹配相应的等级(NewValues),并相应地更新你的表:
WITH OrderedValues AS
( SELECT Value,
Price,
idcategory,
ROW_NUMBER() OVER(PARTITION BY idcategory ORDER BY Value, Price) AS RowNum
FROM T
), OrderedIDs AS
( SELECT ID,
idcategory,
ROW_NUMBER() OVER(PARTITION BY idcategory ORDER BY ID) AS RowNum
FROM T
), NewValues AS
( SELECT i.ID,
v.Value,
v.Price
FROM OrderedIDs i
INNER JOIN OrderedValues v
ON i.RowNum = v.RowNum
AND i.idcategory = v.idcategory
)
UPDATE T
SET Price = v.Price,
Value = v.Value
FROM NewValues v
WHERE v.ID = T.ID;
<强> Example on SQL Fiddle 强>