我有三张桌子Invoice
,Account
并且Visits
每个都有一个共同的主键 ( AccountID
)。我需要为 7 月份没有访问过并且有一个有效帐户以允许该月访问的帐户提取数据(从Invoice
-scheduletype
和Account
-中提取startdate
)
我曾尝试使用多个连接,但无法根据需要获取数据,并且对 SQL 来说还很陌生。有人能帮我指点一下吗?
我有三张桌子Invoice
,Account
并且Visits
每个都有一个共同的主键 ( AccountID
)。我需要为 7 月份没有访问过并且有一个有效帐户以允许该月访问的帐户提取数据(从Invoice
-scheduletype
和Account
-中提取startdate
)
我曾尝试使用多个连接,但无法根据需要获取数据,并且对 SQL 来说还很陌生。有人能帮我指点一下吗?
select A.*
from Accounts A
where A.AccountID NOT IN
(Select V.AcocountID
From Visits V
Where V.date like '%July%' //replace by appropriate condition
) AND
A.AccountID IN
(Select I.AccountID
From Invoice I
Where I.type = Invoice //replace by appropriate condition
) AND
A.startDate< July //replace by appropriate condition
借用上一个答案,您也可以这样做(我更喜欢使用 EXISTS 来查看 AccountID 是否在其中 - 如果有,它会立即停止查找)。
SELECT A.* FROM Accounts A WHERE A.AccountID NOT IN
(SELECT V.AccountID
FROM Visits V
WHERE CONVERT(date, V.date) BETWEEN '2012-07-01' AND '2012-07-31'
-- assuming V.date is a 'datetime'. if V.date is already a 'date' then:
-- WHERE V.date BETWEEN '2012-07-01' AND '2012-07-31'
-- or you could say
-- WHERE NOT(DATEPART(month, V.date) = '7' AND DATEPART(year, V.date) = '2012')
)
AND EXISTS (SELECT *
FROM Invoice I
WHERE I.type = Invoice //or whatever
) AND
A.startDate < '2012-07-01' //or whatever
猜测访问日期,
SELECT a.AccountID
FROM Account a
WHERE NOT EXISTS (
SELECT 1
FROM Invoice i
WHERE i.AccountID = a.AccountID
AND i.ScheduleType = 'hold'
AND i.StartDate < '8/1/2012'
AND i.EndDate >= '7/1/2012'
)
AND NOT EXISTS (
SELECT 1
FROM Visits v
WHERE v.AccountID = a.AccountID
AND v.SessionDate >= '7/1/2012'
AND v.SessionDate < '8/1/2012'
)
AND a.StartDate < '8/1/2012'
AND a.EndDate >= '7/1/2012'
GO
使用以下查询:
Select A.*
From Accounts A
left join visits v on v.AccountID = A.AccountID
AND v.SessionDate >= '2012-07-01'
AND v.SessionDate < '2012-08-01'
left join Invoice I ON I.AccountID = A.AccountID
AND I.ScheduleType = 'hold'
Where V.AccountID IS NULL
and I.AccountID IS NULL
and A.startDate < '2012-07-01'