我有以下语句获得80岁以上的客户
SELECT
C.ClientID,
C.surname + C.forename As Name,
CONVERT(VARCHAR(10), C.DateOfBirth, 103) AS DOB,
S.SchemeID,
[Status]
FROM
vClients C
INNER JOIN
vClientSchemes S ON C.ClientID = S.ClientID
INNER JOIN
vEvents E ON C.ClientId = E.ClientID
WHERE
(DATEDIFF(yy, C.DateOfBirth, GetDate()) -
CASE WHEN((MONTH(DateOfBirth) * 100 + DAY(C.DateOfBirth)) > (MONTH(GetDate()) * 100 + DAY(GetDate())))
THEN 1 ELSE 0 END) > 80
AND (DATEDIFF(yy, DateOfBirth, GetDate()) -
CASE WHEN((MONTH(DateOfBirth) * 100 + DAY(C.DateOfBirth)) >
(MONTH(GetDate()) * 100 + DAY(GetDate())))
THEN 1 ELSE 0 END) < 100
AND C.[Status] = 0
AND S.SchemeID = 3
但是,从结果中我还需要获得它们最后一次被服务使用的日期。这是通过使用以下列
查询表来实现的EventId, EventDate, ClientID
因此,从事件日期使用以下查询。目前我有
SELECT ClientID
FROM vEvents
WHERE EventDate > DATEADD(year,-1,GETDATE())
但是我似乎无法将这两个查询链接起来
where谓词不可sargable,因为您已将列包装在函数中。你可以把这个SARGable AND简化成这样。
WHERE DateOfBirth < DATEADD(Year, -80, cast(getdate() as date)
AND DateOfBirth > DATEADD(Year, -100, cast(getdate() as date)
AND C.[Status] = 0
AND S.SchemeID = 3
对于您的实际问题,您可以使用MAX(EventDate)并按其余列分组,或者您可以使用ROW_NUMBER。
看起来您已经通过别名E
访问了查询中的vEvents
表。您应该能够通过添加:
AND E.EventDate > DATEADD(year, -1, GETDATE())
ClientID
应该是相同的vEvents
表,因为它是从你的vClients
表,由于内部连接,你已经选择了它。
是的,marc_2你是对的,只需要添加条件和一个distinct,但是删除EventDate上的select
SELECT
distinct C.ClientID,
C.surname + C.forename As Name,
CONVERT(VARCHAR(10), C.DateOfBirth, 103) AS DOB
FROM vClients C
inner join vClientSchemes S on C.ClientID = S.ClientID
inner join vEvents E ON C.ClientId = E.ClientID
WHERE
(DATEDIFF(yy,C.DateOfBirth,GetDate()) -
CASE WHEN((MONTH(DateOfBirth)*100 + DAY(C.DateOfBirth)) > (MONTH(GetDate())*100 + DAY(GetDate()))) THEN 1 ELSE 0 END)> 80
AND (DATEDIFF(yy,DateOfBirth,GetDate()) - CASE WHEN((MONTH(DateOfBirth)*100 + DAY(C.DateOfBirth)) > (MONTH(GetDate())*100 + DAY(GetDate()))) THEN 1 ELSE 0 END) <100
AND C.[Status] = 0 AND S.SchemeID = 3 AND EventDate > DATEADD(year,-1,GETDATE()) order by C.clientid