sql - 为上个月的每个组选择 10%
问题描述
我可以使用前一个月的前 10%
select top 10 percent ID, Ref, Entered_Date, [Type], CREATEDBY, Office, Created_Date, Amt from Tbl
where DATEPART(m, Entered_Date) = DATEPART(m, DATEADD(m, -1, getdate())) AND DATEPART(yyyy, Entered_Date) = DATEPART(yyyy, DATEADD(m, -1, getdate())) and
CreatedBy ='User1')
order by amt DESC
对于使用联合的每个用户,我必须多次执行此操作,如何在一个查询中执行此操作?当我添加其他用户 CreatedBy in('User1','User2') 它不起作用。我查看了分区上的行,但无法弄清楚。我正在使用 SSMS 2017。
更新如下
Select * From(
select ID, Ref, Entered_Date, [Type], CREATEDBY, Office, Created_Date, Amt
NTILE (10) OVER ( PARTITION BY CREATEDBY ORDER BY Amt desc) AS PercentageNo
from Tbl
where DATEPART(m, Entered_Date) = DATEPART(m, DATEADD(m, -1, getdate())) AND DATEPART(yyyy, Entered_Date) = DATEPART(yyyy, DATEADD(m, -1, getdate()))
/*Entered_Date between DATEADD(m, -2, getdate()) and DATEADD(m, -1, getdate()) */ )as SubQuery
where PercentageNo=1 order By Amt
解决方案
您可以使用GROUP BY
每个用户的选择百分比,如下所示:
select top 10 percent ID, Ref, Entered_Date, [Type], CREATEDBY, Office, Created_Date, Amt
FROM Tbl
where DATEPART(m, Entered_Date) = DATEPART(m, DATEADD(m, -1, getdate()))
AND DATEPART(yyyy, Entered_Date) = DATEPART(yyyy, DATEADD(m, -1, getdate()))
AND CreatedBy IN ('User1','User2')
GROUP BY ID, Ref, Entered_Date, [Type], CREATEDBY, Office, Created_Date, Amt
order by amt DESC
推荐阅读
- javascript - 无法访问 js 对象属性
- android - React-native 错误:命令失败:./gradlew app: installDebug -PreactNativeDevServerPort = 8081
- java - Spring 批量集成测试
- python - 在 kivy 中检查子交互的语法
- r - 删除打印到文件中的多余行
- deep-learning - 改变学习率后,我们应该如何缩放权重衰减系数?
- nixos - 如何在nixos20.09上安装libmysqlclient.so.18?
- python - 读取 GCP 中以 blob 形式存在的 json 数据时出错。错误:json.decoder.JSONDecodeError:预期值:第 1 行第 1 列(字符 0)
- powershell - powersehll 中的变量、比较和运算符
- asp.net-mvc - 对如何通过 ViewBag 填充 DropDown 感到困惑