创建新列并用相同的字段值填充所有行
Create new column and fill all rows with the same field values
我有一个对服装进行评分的数据库。我想在预测月份 = 基准月份时取预测评级的值,并将其填充到名为实际评级的新列中具有相同基准月份、衬衫、裤子和鞋子的行中,如下所示。
predicted month
base month
shirt
pants
shoes
predicted rating
4
0
1
1
1
0.1
3
0
1
1
1
0.2
0
0
1
1
1
0.5
1
1
2
2
1
0.6
5
1
2
2
1
0.3
4
1
2
2
1
0.1
我将预测月份 = 基准月份的行加粗了。
例如。由于前两行与第三行具有相同的基准月份、衬衫、裤子、鞋子,其预测月份 = 基准月份,我想采用第三行的预测评级并将其填入第 1-3 行的实际评级。我该怎么做?
例如。我想将第 4 行的预测评分填入第 5-6 行的实际评分
predicted month
base month
shirt
pants
shoes
predicted rating
Actual rating
4
0
1
1
1
0.1
0.5
3
0
1
1
1
0.2
0.5
0
0
1
1
1
0.5
0.5
1
1
2
2
1
0.6
0.6
5
1
2
2
1
0.3
0.6
4
1
2
2
1
0.1
0.6
没有排序数据库的顺序。最后一行可能是第一行。
我试过分区并寻找方法来做到这一点仍然不知道如何。 SQL 这可能吗?提前致谢。
我们可以使用ROW_NUMBER
结合条件聚合。此答案假定每组的“第三”行的特征是具有最早的预测月份值。
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY [base month], shirt, pants, shoes
ORDER BY [predicted month]) rn
FROM yourTable
)
SELECT [predicted month], [base month], shirt, pants, shoes, [predicted rating],
MAX(CASE WHEN rn = 1 THEN [predicted rating] END)
OVER (PARTITION BY [base month], shirt, pants, shoes) AS [Actual rating]
FROM cte
ORDER BY [base month], shirt, pants, shoes, [predicted month] DESC;
看起来你可以使用 First_Value():
select *,
First_Value(predictedRating) over(partition by baseMonth order by predictedMmonth) as ActualRating
from t;
我有一个对服装进行评分的数据库。我想在预测月份 = 基准月份时取预测评级的值,并将其填充到名为实际评级的新列中具有相同基准月份、衬衫、裤子和鞋子的行中,如下所示。
predicted month | base month | shirt | pants | shoes | predicted rating |
---|---|---|---|---|---|
4 | 0 | 1 | 1 | 1 | 0.1 |
3 | 0 | 1 | 1 | 1 | 0.2 |
0 | 0 | 1 | 1 | 1 | 0.5 |
1 | 1 | 2 | 2 | 1 | 0.6 |
5 | 1 | 2 | 2 | 1 | 0.3 |
4 | 1 | 2 | 2 | 1 | 0.1 |
我将预测月份 = 基准月份的行加粗了。
例如。由于前两行与第三行具有相同的基准月份、衬衫、裤子、鞋子,其预测月份 = 基准月份,我想采用第三行的预测评级并将其填入第 1-3 行的实际评级。我该怎么做?
例如。我想将第 4 行的预测评分填入第 5-6 行的实际评分
predicted month | base month | shirt | pants | shoes | predicted rating | Actual rating |
---|---|---|---|---|---|---|
4 | 0 | 1 | 1 | 1 | 0.1 | 0.5 |
3 | 0 | 1 | 1 | 1 | 0.2 | 0.5 |
0 | 0 | 1 | 1 | 1 | 0.5 | 0.5 |
1 | 1 | 2 | 2 | 1 | 0.6 | 0.6 |
5 | 1 | 2 | 2 | 1 | 0.3 | 0.6 |
4 | 1 | 2 | 2 | 1 | 0.1 | 0.6 |
没有排序数据库的顺序。最后一行可能是第一行。
我试过分区并寻找方法来做到这一点仍然不知道如何。 SQL 这可能吗?提前致谢。
我们可以使用ROW_NUMBER
结合条件聚合。此答案假定每组的“第三”行的特征是具有最早的预测月份值。
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY [base month], shirt, pants, shoes
ORDER BY [predicted month]) rn
FROM yourTable
)
SELECT [predicted month], [base month], shirt, pants, shoes, [predicted rating],
MAX(CASE WHEN rn = 1 THEN [predicted rating] END)
OVER (PARTITION BY [base month], shirt, pants, shoes) AS [Actual rating]
FROM cte
ORDER BY [base month], shirt, pants, shoes, [predicted month] DESC;
看起来你可以使用 First_Value():
select *,
First_Value(predictedRating) over(partition by baseMonth order by predictedMmonth) as ActualRating
from t;