我想通过查看积分奖励字段,奖励金牌和银牌(即在适用的情况下值为1,否则为0)至前2名。
我已经创建了第一个表。我想要一个带有两个新字段的新表,即金色和银色字段。
请帮我查询或提供一些有关如何继续的建议。
非常感谢。
答案 0 :(得分:1)
我认为你想使用dense_rank()
:
select t.*,
(case when rnk = 1 then 1 else 0 end) as gold,
(case when rnk = 2 then 1 else 0 end) as silver
from (select t.*,
dense_rank() over (partition by week order by pointsrewarded) as rnk
from t
) t;
当有关系时, dense_rank()
会处理此案。在这种情况下,将分配多个“黄金”和“白银”值。
我还应该注意,子查询不是必需的。您可以在外部查询中重复dense_rank()
。我只是觉得以这种方式遵循逻辑更容易。
答案 1 :(得分:0)
确保按指数降序排序,因此第一个位置是最高点而不是最低点。我的代码更长,但我觉得更容易阅读(个人偏好)。
--create table employee (employeeid int, employeename varchar(50), weeknumber int, pointsRewarded int, Hours int)
--insert into employee values (111, 'person1', 1, 400, 2)
--insert into employee values (112, 'person2', 1, 100, 10)
--insert into employee values (113, 'person3', 1, 200, 10)
--insert into employee values (111, 'person1', 2, 100, 2)
--insert into employee values (112, 'person2', 2, 50, 10)
--insert into employee values (113, 'person3', 2, 200, 10)
--insert into employee values (111, 'person1', 3, 20, 4)
--insert into employee values (112, 'person2', 3, 25, 5)
--insert into employee values (113, 'person3', 3, 100, 6)
;WITH Medals AS
(
SELECT
employeeid
,employeename
,weeknumber
,pointsRewarded
,hours
,ROW_NUMBER() OVER (PARTITION BY weeknumber ORDER BY pointsrewarded DESC) medal
FROM
employee
)
SELECT
employeeid
,employeename
,weeknumber
,pointsRewarded
,hours
,CASE WHEN medal = 1 THEN 1 ELSE 0 END AS gold
,CASE WHEN medal = 2 THEN 1 ELSE 0 END AS silver
FROM
Medals