我有三个表Invoice
,Account
和Visits
每个都有一个共同的主键(AccountID
)。我需要为7月份没有访问过的帐户提取数据,并拥有一个有效的帐户以允许在该月访问(来自Invoice
- scheduletype
和Account
- startdate
)
我尝试过使用多个连接,但是由于我需要它而无法获取数据,而且我对SQL很新。请问有人可以帮我解决一些问题吗?
答案 0 :(得分:0)
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
答案 1 :(得分:0)
借用上一个答案,您也可以这样做(我更喜欢使用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
答案 2 :(得分:0)
猜测访问日期,
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
答案 3 :(得分:0)
使用以下查询:
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'