我使用这种结构创建表约会:
CREATE TABLE Appointments
(
[Id] bigint,
[Name] varchar(250),
[DateInit] date
);
INSERT INTO Appointments ([Id], [Name], [DateInit])
values
(1000, 'Lorena', '03/06/2016'),
(1000, 'Lorena', '01/06/2016'),
(1000, 'Lorena', '08/06/2016'),
(1000, 'Lorena', '10/06/2016'),
(1000, 'Lorena', '02/06/2016'),
(1000, 'Lorena', '20/06/2016'),
(7000, 'Susan', '04/06/2016'),
(7000, 'Susan', '08/06/2016'),
(7000, 'Susan', '09/06/2016'),
(7000, 'Susan', '01/06/2016');
这是最终结果:
我需要在第二天和前一天得到结果,例如,如果今天是2016年06月06日'我需要从今天开始在表格中插入最后一个约会的结果,从今天开始在表格中插入下一个约会,我需要的结果是这样的:
Name Last Visit Next Visit
----- ---------- -----------
Lorena 2016-06-02 2016-06-08
Susan 2016-06-01 2016-06-04
我怎样才能得到这个结果? 感谢
答案 0 :(得分:7)
执行GROUP BY
,使用case
表达式选择最后一次约会,并将未来的约会分开:
select name,
max(case when DateInit < CONVERT(DATE,GETDATE()) then DateInit end) as LastVisit,
min(case when DateInit > CONVERT(DATE,GETDATE()) then DateInit end) as NextVisit
from Appointments
group by name
答案 1 :(得分:3)
我这样做是为了加入上一次和下一次访问,就像这样;
SELECT DISTINCT
a.ID
,a.NAME
,l.LastVisit
,n.NextVisit
FROM Appointments a
LEFT JOIN (
SELECT ID
,MIN(DateInit) NextVisit
FROM Appointments
WHERE DateInit > GETDATE()
GROUP BY ID
) n ON a.ID = n.ID
LEFT JOIN (
SELECT ID
,MAX(DateInit) LastVisit
FROM Appointments
WHERE DateInit < GETDATE()
GROUP BY ID
) l ON a.ID = l.ID
答案 2 :(得分:1)
DECLARE @Appointments TABLE
(
[Id] bigint,
[Name] varchar(250),
[DateInit] date
);
INSERT INTO @Appointments ([Id], [Name], [DateInit])
values
(1000, 'Lorena','2016/06/03'),
(1000, 'Lorena','2016/06/01'),
(1000, 'Lorena','2016/06/08'),
(1000, 'Lorena','2016/06/10'),
(1000, 'Lorena','2016/06/02'),
(1000, 'Lorena','2016/06/20'),
(7000, 'Susan', '2016/06/04'),
(7000, 'Susan', '2016/06/08'),
(7000, 'Susan', '2016/06/09'),
(7000, 'Susan', '2016/06/01');
DECLARE @Today DATE = GETDATE();
WITH CTE
AS (
SELECT A.NAME
,ROW_NUMBER() OVER (
PARTITION BY ID ORDER BY ID
) RN
,(
SELECT TOP 1 DateInit
FROM @Appointments B
WHERE B.ID = A.ID
AND DateInit < @TODAY
ORDER BY DateInit DESC
) [Last Visit]
,(
SELECT TOP 1 DateInit
FROM @Appointments B
WHERE B.ID = A.ID
AND DateInit > @TODAY
ORDER BY DateInit
) [Next Visit]
FROM @Appointments A
--GROUP BY ID
)
SELECT C.NAME
,C.[Last Visit]
,C.[Next Visit]
,RN
FROM CTE C
WHERE RN = 1