Демонстрация на дб <> скрипка
Вы можете использовать datepart(wk, date)
, чтобы получить неделю в году.
;with t1 as ( -- Exclude customer comeback in the same date
select distinct userid, date
from #table1
),
t2 as (-- Get week in year
select userid, 'Week ' + cast(datepart(wk, date) as varchar(2)) Week
from t1
)
select userid, Week, count(*) as numberOfVisit -- group by userId and week in year
from t2
group by userid, Week
having count(*) > 1
Вы также можете Подсчитать всех клиентов , чтобы получить последний результат.
;with t1 as (
select distinct userid, date
from #table1
),
t2 as (
select userid, 'Week ' + cast(datepart(wk, date) as varchar(2)) Week
from t1
),
t3 as (
select userid, Week, count(*) as numberOfVisit
from t2
group by userid, Week
having count(*) > 1)
select count(*) Total
from t3