我想提取May和JUNE中存在但JULY中不存在的那些帐户ID。我有6个月的数据
我尝试使用CONDITION(AND / NOT)
SELECT ACCOUNT_ID, DATA_MONTH
FROM DATA1
WHERE DATA_MONTH ='01-MAY-18' AND DATA_MONTH <> '01-JULY-18
GROUP BY DATA_MONTH
我仍然在7月的哪个位置获得帐户ID
答案 0 :(得分:1)
您可以将所需的条件放在HAVING
子句中:
SELECT ACCOUNT_ID
FROM DATA1
GROUP BY ACCOUNT_ID
HAVING
SUM(CASE WHEN MONTH(DATA_MONTH) = 5 THEN 1 ELSE 0 END) > 0
AND
SUM(CASE WHEN MONTH(DATA_MONTH) = 6 THEN 1 ELSE 0 END) > 0
AND
SUM(CASE WHEN MONTH(DATA_MONTH) = 7 THEN 1 ELSE 0 END) = 0
我假设您的rdbms中有一个类似MONTH()
的函数可以从日期中提取月份。
如果还要检查年份,则可以在每种情况下都进行检查,因此必须更改为:
CASE WHEN MONTH(DATA_MONTH) = 7 AND YEAR(DATA_MONTH) = 2018 THEN 1 ELSE 0
答案 1 :(得分:0)
您的日期格式看起来像Oracle,因此我将为该数据库回答。
想法是使用条件聚合:
SELECT ACCOUNT_ID, DATA_MONTH
FROM DATA1
WHERE DATA_MONTH >= DATE '2018-05-01' AND
DATA_MONTH < DATE '2018-08-01'
GROUP BY ACCOUNT_ID
HAVING COUNT(DISTINCT DATA_MONTH) = 2 AND
MAX(DATA_MONTH) < DATE '2018-07-01';
这假设您的所有日期都在该月的第一天。
答案 2 :(得分:0)
使用SQL Server的Month函数为您提供了一个解决此问题的易于理解的示例。
SELECT ACCOUNT_ID
FROM DATA1
WHERE MONTH(DATA_MONTH) in (5,6) AND YEAR(DATA_MONTH) = 2018 AND MONTH(DATA_MONTH) NOT IN (7)
GROUP BY ACCOUNT_ID
答案 3 :(得分:0)
SELECT ACCOUNT_ID, DATA_MONTH
FROM DATA1
WHERE MONTH(DATA_MONTH) =5 AND MONTH(DATA_MONTH) = 6
GROUP BY DATA_MONTH
答案 4 :(得分:0)
SELECT ACCOUNT_ID, DATA_MONTH
FROM DATA1
WHERE MONTH(DATA_MONTH) BETWEEN 5 AND 6
GROUP BY Year(DATA_MONTH),month(DATA_MONTH)