我必须编写一个SQL查询,我很困惑,我可以通过自联接或使用内部查询来解决它。
我有一个包含列的表
UserID, DateSubscription, Status
Status
可以是'E'
或'R'
。
我必须选择subscription Date between Date1 and Date2
且UserID
不应加载Status = 'E'
且不在Date1
和Date2
之间的日期范围内的用户的用户
UserID
可以存在多个状态不同的行
以下是我试过的查询
SELECT
IDNO,
IND_ID,
IND_SRC,
EXPIRY_DATE,
RECSTA
FROM
VIND,
VSCR
WHERE
VIND.IND_ID = VSCR.IND_ID
AND
VIND.IND_SRC = VSCR.IND_SRC
AND
EXPIRY_DATE >= '2015-04-25'
AND
EXPIRY_DATE <= '2015-06-25'
AND
(
RECSTA <> 'E'
AND
EXPIRY_DATE > '2015-06-25'
)
答案 0 :(得分:0)
如果我理解正确,您希望所有有效期限在A和B之间的记录,以及状态不是E
select *
from yourtable
where EXPIRY_DATE between @startDateParam and @endDateParam
or [Status] <> 'E'
答案 1 :(得分:0)
试试这个。
select UserID, DateSubscription
from table
where DateSubscription between @startDate and @endDate and
(Status <> 'E' OR DateSubscription not between @startDate and @endDate)
答案 2 :(得分:0)
我使用NOT EXISTS
来检查第二项要求
SELECT
UserID
FROM
Subscriptions
WHERE
DateSubscription BETWEEN @date1 and @date2
AND NOT EXISTS
(SELECT
NULL
FROM
Subscriptions OtherSubscriptions
WHERE
-- Get UserIDs other rows
Subscriptions.UserID = OtherSubscriptions.UserID
-- Only rows that have status 'E'
AND OtherSubscriptions.Status = 'E'
-- subscription is before @date1 or after @date2
AND (OtherSubscriptions.DateSubscription < @date1
OR OtherSubscriptions.DateSubscription > @date2)
答案 3 :(得分:0)
执行此操作的一种方法是group by
上的userid
并使用HAVING
和CASE
过滤数据。
SELECT UserID, DateSubscription, Status
FROM UserStatusTable
GROUP BY UserID
HAVING SUM(CASE WHEN DateSubscription BETWEEN Date1 AND Date2 THEN 1 ELSE 0 END) > 1
AND SUM(CASE WHEN DateSubscription NOT BETWEEN Date1 AND Date2 AND Status = 'E' THEN 1 ELSE 0 END) = 0