【发布时间】:2016-01-21 09:36:54
【问题描述】:
美好的一天!
我有一个使用 SQL 的查询,它给出了每个租户的销售结果集。现在,我想得到一个最终结果集,显示销售额前 5 名和后 5 名(可能灵活,但以 5 为例)
我使用 rank 函数来获得每个销售额的排名,并且能够通过根据销售额显示顶部和底部的租户来获得几乎想要的输出。
这是存储过程的部分代码
@RankedBy int = 5
SELECT *FROM (
SELECT #TEMPTABLE5.*, 'BOTTOM' AS 'RankName' ,
Rank() over (Partition BY Business ORDER BY Sales ) AS Rank
FROM #TEMPTABLE5
) rs WHERE Rank <= @RankedBy
UNION ALL
SELECT *FROM (
SELECT #TEMPTABLE5.*, 'BOTTOM' AS 'RankName' ,
Rank() over (Partition BY Business ORDER BY Sales DESC ) AS Rank
FROM #TEMPTABLE5
) rs WHERE Rank <= @RankedBy
order by Business, RankName DESC ,Rank
这是结果集
tenant business sales rankName rank
sample A1 food 1500 top 1
sample A2 food 1400 top 2
sample A3 food 1300 top 3
sample A4 food 1200 top 4
sample A5 food 1100 top 5
sample A6 food 100 bottom 1
sample A7 food 200 bottom 2
sample A8 food 300 bottom 3
sample A9 food 400 bottom 4
sample A10 food 500 bottom 5
sample B1 non food 2000 top 1
sample B2 non food 1800 top 2
sample B3 non food 1500 top 3
sample B3 non food 1500 bottom 1
sample B2 non food 1800 bottom 2
sample B1 non food 2000 bottom 3
根据给定的信息,我已经实现了基于 NUMBER ASSIGNED IN @RankedBy Parameter 获得顶部和底部。
我现在想要的是有一个条件,如果每个企业的结果集低于或小于参数@RankedBy,则结果不应再包括底部,就像这样样本正确结果:
tenant business sales rankName rank
sample A1 food 1500 top 1
sample A2 food 1400 top 2
sample A3 food 1300 top 3
sample A4 food 1200 top 4
sample A5 food 1100 top 5
sample A6 food 100 bottom 1
sample A7 food 200 bottom 2
sample A8 food 300 bottom 3
sample A9 food 400 bottom 4
sample A10 food 500 bottom 5
sample B1 non food 2000 top 1
sample B2 non food 1800 top 2
sample B3 non food 1500 top 3
non food 只有 3 条记录,小于 @RankedBy 中指定的参数 5。
在我现有的代码中,我计划对每个业务进行计数并将条件放在 where 子句中,但我发现它效率低下且无效。
如果你们专家中的任何人可以提供更有效的编码或可以更正我的初始代码。
提前致谢
【问题讨论】:
标签: sql sql-server sql-server-2008 data-partitioning