计算SQL中2列之间的月差

时间:2015-03-16 06:25:05

标签: sql

我需要从我的select语句中排除一些没有5个月历史记录的帐户

enter image description here

在图片中,我必须排除' A'如果第一行和第五行中的日期差异小于5个月,则在前5行中。同样适用于Alli,L,O,R等

2 个答案:

答案 0 :(得分:1)

DISTINCTGROUP BY

一起使用

MSSQL

SELECT Ori FROM TableName
GROUP BY Ori
HAVING COUNT(DISTINCT CONVERT(NVARCHAR(6), Date, 112)) >= 5

或者

SELECT Ori FROM TableName
GROUP BY Ori
HAVING DATEDIFF(mm, MIN(Date), MAX(Date)) >= 5

ORACLE

SELECT Ori FROM TableName
GROUP BY Ori
HAVING COUNT(DISTINCT TO_CHAR(Date, 'yyyymm')) >= 5

答案 1 :(得分:0)

使用datediff(月,,)

示例代码:

select max (date) as maxdate, min(date) as mindate, Ori into #temp from table group by Ori

delete from table where Ori in (select Ori from #temp where datediff (month, mindate, maxdate) < 5)
drop table #temp