Вот статическая версия (из коулиги):
with c as (
select
p.id_doc,
p.id_usr,
DATEDIFF(DAY, p.created_at, getdate()) as date_diff
from Document p
where 1 = 1
), p as (
select
pvt.id_usr,
[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]
from c
PIVOT (COUNT(c.id_doc) FOR c.date_diff IN ([0], [1], [2], [3], [4], [5], [6], [7], [8], [9])) AS pvt
)
select
u.username,
u.name,
[0], [1], [2], [3], [4], [5], [6], [7], [8], [9],
y.nr,
y.total_money
from p
inner join Users u on u.id_usr = p.id_usr
cross apply (
select
COUNT(1) as nr,
SUM(premium) as total_money
from Document z
where z.id_usr = p.id_usr
) as y
order by nr desc