select *
from
(
select year,
week,
salesperson,
count(*) as transactions,
rank() over(partition by week order by count(*) desc) as ranking
from sales
where year = '2010',
group by year,
week,
salesperson
) temp
where ranking <= 10
查询返回一年中每个星期的前十名销售人员(按交易数量计)的列表。
如何在我的结果中添加列:
你能就如何解决这些问题提出一般性建议吗?
PS:使用SQL Server 2008
答案 0 :(得分:1)
实际上,我不相信Views是最好的方式。您可以在CTE中执行此类逻辑,并将整个事物组合到一个查询中。例如,除了连续逻辑之外,这里有我所拥有的一切:
;With
SalesDateParts As
(
Select DatePart(wk, SaleDate) As WeekNum, DatePart(yy, SaleDate) As [Year], SalesPersonId
From #Sales
)
, SalesByWeek As
(
Select [Year], WeekNum, SalesPersonId, Count(*) As SaleCount
, RANK() OVER( PARTITION BY [Year], [WeekNum] ORDER BY Count(*) DESC ) As SaleRank
From SalesDateParts
Group By [Year], WeekNum, SalesPersonId
)
, PrevWeekTopSales As
(
Select [Year], [WeekNum], SalesPersonId, SaleCount
From SalesByWeek
Where [Year] = DatePart(yyyy, DateAdd(d, -7, CURRENT_TIMESTAMP))
And WeekNum = DatePart(wk, DateAdd(d, -7, CURRENT_TIMESTAMP))
)
, WeeksInTop10 As
(
Select SalesPersonId, Count(*) As Top10Count
From SalesByWeek
Where SaleRank <= 10
Group By SalesPersonId
)
Select *
From Salespersons
Left Join WeeksInTop10
On WeeksInTop10.SalesPersonId = SalesPersons.SalesPersonId
Left Join PrevWeekTopSales
On PrevWeekTopSales.SalesPersonId = SalesPersons.SalesPersonId
“连续”的逻辑可能需要一个日历表,其中包含每天的值以及给定日期的年份和星期的列。
答案 1 :(得分:0)
我的建议是在视图中单独执行其他查询,然后由销售人员加入(我认为这是关键)
逻辑是这个查询很好,干净,易于遵循。否则 - 我认为攻击它的方法是开始编写TSQL函数来计算其他值,但我认为这些函数无论如何都会有查询。