为我的跳伞俱乐部做一些统计页面我有两个想要合并的SQL查询。 其中一个显示了今年第一次加载跳跃最多的三个跳投:
select top 3 ROW_NUMBER() OVER(ORDER BY count(1) desc) AS Nr
, vc.sCust as Name
, count(1) as JumpsCount
from dbo.ViewInvoice vi with(nolock)
join dbo.viewCust vc
on vi.wCustId = vc.wCustId
where year(vi.dtProcess) = year(getdate())
and vi.nMani = 1
group by vc.sCust
order by count(1) desc
输出:
-- Nr Name JumpsCount
-- 1 Tom Awesome 17
-- 2 Alan Jackson 16
-- 3 John Thebest 13
下一个查询显示了在数据库中跳跃的所有年份:
select distinct year(vi.dtProcess) As Datum
from dbo.ViewInvoice vi
order by 1
输出:
-- Datum
-- 2010
-- ...
-- 2014
我想要的是获得一个查询,将结果与这样的输出合并:
-- Datum Nr Name Jumpscount
-- 2010 1 Some OldVeteran 100
-- 2010 2 Alan Jackson 96
-- 2010 3 Gordon McGann 89
-- ...
-- 2014 1 Tom Awesome 17
-- 2014 2 Alan Jackson 16
-- 2014 3 John Thebest 13
答案 0 :(得分:1)
更改为RANK
,因此具有相同跳跃量的跳投得到相同的位置。
WITH JumpsPerYear AS (
SELECT YEAR(dtProcess) AS [Year]
,wCustId
,COUNT(1) AS JumpsCount
FROM ViewInvoice
WHERE nMani = 1 -- first load/manifest number
GROUP BY YEAR(dtProcess)
,wCustId
)
,RankPerYear AS (
SELECT [Year]
,wCustId
,RANK() OVER (PARTITION BY [Year] ORDER BY JumpsCount DESC) AS [Rank]
,JumpsCount
FROM JumpsPerYear
)
SELECT RankPerYear.[Year] AS Datum
,RankPerYear.[Rank] AS Nr
,ViewCust.sCust AS Name
,RankPerYear.JumpsCount
FROM RankPerYear
INNER JOIN ViewCust
ON ViewCust.wCustId = RankPerYear.wCustId
WHERE RankPerYear.[Rank] <= 3
ORDER BY RankPerYear.[Year]
,RankPerYear.[Rank]