Rank_Table
ID Rank
1 1
2 1
3 3
4 3
5 5
价格
No Points
1 10
2 9
3 8
4 7
5 6
预期产出
ID Rank Points
1 1 9.5
2 1 9.5
3 3 7.5
4 3 7.5
5 5 6
第2级不存在所以第1和第2点是总和并且在学生的数量之间分配 例如:(10 + 9)/ 2 = 9.5
当我加入2表时,如
select *
from Rank_table a join
Price b
on a.ID = b.No
我的输出为
ID Rank No Points
1 1 1 10
2 1 2 9
3 3 3 8
4 3 4 7
5 5 5 6
答案 0 :(得分:3)
这似乎是一个非常简单的要求,只需使用AVG
和OVER
子句。
CREATE TABLE [Rank] (ID int, [Rank] int)
CREATE TABLE Price ([No] int, Points int);
GO
INSERT INTO [Rank]
VALUES
(1,1),
(2,1),
(3,3),
(4,3),
(5,5);
INSERT INTO Price
VALUES
(1,10),
(2,9),
(3,8),
(4,7),
(5,6);
GO
SELECT R.ID,
R.[Rank],
AVG(CONVERT(decimal(2,0),P.Points)) OVER (PARTITION BY R.[Rank]) AS Points
FROM [Rank] R
JOIN Price P ON R.ID = P.[No];
GO
DROP TABLE [Rank];
DROP TABLE Price;
答案 1 :(得分:2)
您需要简单的JOIN
:
select rn.*,
avg(convert(decimal(10,0), p.Points)) over (partition by rn.rnk) as points
from Rank_Table rn inner join
Price p
on p.id = rn.No;
答案 2 :(得分:0)
嗯。你似乎想要一个基于“下一个”等级的非等值连接以及每一行中的等级。遗憾的是,SQL Server 2008不支持lead()
,但您可以使用apply
:
select rt.id, rt.rank, avg(p.price * 1.0) as points
from rank_table rt outer apply
(select min(rt2.rank) as next_rank
from rank_table rt2
where rt2.rank > rt.rank
) rt2 left join
price p
on p.no >= rt.rank >= p.no and
(p.no < rt2.next_rank or rt2.next_rank is null)
group by rt.id, rt.rank;
答案 3 :(得分:0)
TableA
答案 4 :(得分:0)
您可以在排名级别计算AVG,然后加入Rank_Table,就像 working demo
一样select R.*,T.points from Rank_table R
JOIN
(
select rank, points=avg(cast(points as decimal(10,2)))
from Rank_table a join
Price b
on a.ID = b.No
group by rank
)T
on T.rank=R.rank