我希望仅当该服务日期与客户首次服务匹配时才跳过每个客户的第一个服务日期。
例如,如果客户注册1-04-2017
client enrollment date service date摘要页面的预期结果
sam 1-04-2017 1-04-2017 sam 1-04-2017 1-04-2017 jon 1-04-2017 1-04-2017
jon 1-04-2017 1-05-2017 sam 1-04-2017 1-05-2017
jon 1-04-2017 1-07-2017
total clients total services 2 4
我希望查看详细信息时的预期结果
client enrollment date service date
sam 1-04-2017 1-04-2017 jon 1-04-2017 1-05-2017 sam 1-04-2017 1-05-2017
jon 1-04-2017 1-07-2017
此外,您的客户还有一个注册但多个服务。 考虑到查询将被上传到ssrs并且服务日期将是@begindate和@enddate之间的变量s.begindate,我如何跳过查询的第一个服务日期。
答案 0 :(得分:0)
根据您的描述,您似乎想要一个使用窗口函数的简单where
子句:
select t.*
from (select t.*,
min(enrollment_date) over (partition by client) as first_enrollment_date
from t
) t
where first_enrollment_date > service_date;
但是,这只会留下两项服务,所以目前还不清楚你真正想要的是什么。
答案 1 :(得分:0)
根据您提供的内容,这是我猜你需要的。
CREATE TABLE T (id int identity, client varchar(10), enrollment_date date, service_date date)
--client enrollment date service date
INSERT INTO T VALUES
('sam','1-04-2017','1-04-2017'),
('sam','1-04-2017','1-04-2017'),
('jon','1-04-2017','1-04-2017'),
('jon','1-04-2017','1-05-2017'),
('sam','1-04-2017','1-05-2017'),
('jon','1-04-2017','1-07-2017')
DECLARE @StartDate date = '1-04-2017', @EndDate date = '1-07-2017'
SELECT COUNT(DISTINCT client) AS total_clients, COUNT(1)-COUNT(DISTINCT client) AS total_services
FROM T
WHERE service_date BETWEEN @StartDate AND @EndDate
SELECT DISTINCT T.*
FROM T T JOIN (SELECT client, MIN(id) AS enroll_id FROM T GROUP BY client) E
ON T.client = E.client
AND T.id <> E.enroll_id
WHERE service_date BETWEEN @StartDate AND @EndDate
ORDER BY 2, 3
DROP TABLE T
这是我从中得到的新结果。
total_clients total_services
------------- --------------
2 4
id client enrollment_date service_date
----------- ---------- --------------- ------------
4 jon 2017-01-04 2017-01-05
6 jon 2017-01-04 2017-01-07
2 sam 2017-01-04 2017-01-04
5 sam 2017-01-04 2017-01-05
这只会从总体计数中减去不同的客户端数量,以抵消注册事件。
希望这可以帮助你。