sql - 使用 case 语句并为每条前 10 条记录设置不同的值
问题描述
我有一个表,它返回包含两列的记录列表:
SELECT Id, Duration from dbo.[VW_ActivityDuration] ORDER BY DURATION desc
我想使用该case
语句并为每前 10 条记录设置不同的值,按DURATION降序排列。
例子:
set the value as 5 for the first 10 records
and set the value as 4 for the next 10 records
and set the value as 3 for the other next 10 records
and set the value as 2 for the other next 10 records
同样,在那之后我必须为 all 设置值 1
SELECT TOP (1000) [Id]
,[Name],
CASE
WHEN --- THEN '5'
ELSE '1'
END AS [Value]
FROM [EngagementDb].[dbo].[VW_ActivityDuration]
ORDER BY [DurationMinutes] desc
任何先机、提示或建议将不胜感激。我无法开始编写查询来解决这个问题。
解决方案
我想你想要row_number()
一个case
表达:
select id, DurationMinutes,
case
when row_number() over(order by DurationMinutes desc) <= 10 then 5
when row_number() over(order by DurationMinutes desc) <= 20 then 4
when row_number() over(order by DurationMinutes desc) <= 30 then 3
when row_number() over(order by DurationMinutes desc) <= 40 then 2
else 1
end as val
from [EngagementDb].[dbo].[VW_ActivityDuration]
order by DurationMinutes desc
我们可以用算术把它缩短一点:
select id, DurationMinutes,
case when row_number() over(order by DurationMinutes desc) <= 40
then 5 - (row_number() over(order by DurationMinutes desc) - 1) / 10
else 1
end as val
from [EngagementDb].[dbo].[VW_ActivityDuration]
order by DurationMinutes desc
推荐阅读
- javascript - 使用 Javascript 和单选按钮显示文本文件
- javascript - 在段落标记内插入选定文本的 HTML 标记
- ruby-on-rails - 共享点提供商在 Visual Studio 2017 中托管应用程序以在组织级别发布
- java - Spring RequestMapping 不会在 .jsp 请求上触发
- ios - 在使用 swift 的 iOS 中,如何创建一个始终位于整个应用程序顶部的可拖动和浮动 UIView
- python - Jupyter notebook 多窗口输出
- ios - 用动画在 UIImageView 上显示多个图像
- android - Android:使用 webview 捕获图像
- android - 使用滑行从 gif 图像中删除透明的白色背景?
- firebase - Firebase 规则不起作用。即使我在 Firestore 中设置规则也返回数据