日期:2014-05-17  浏览次数:20593 次

请问如何才能得到这样的数据结果?
字段:

ID usename A_Date B_Date C_Date
1 aa 2012-7-9 2012-8-15 2012-4-13
2 bb 2012-7-9 2012-8-8 2012-7-23
3 cc 2012-6-25 2012-9-5 2012-8-13

一共有3个日期字段,想得到三个日期的字段相差大于1个月的数据统计结果。

例如,这儿要求得到的结果应该是数据id1的,因为这条记录3个日期相差都大于1个月(按30天算)。

请问sql语句应该怎么写?

难道真的要用程序一个一个去搜索,循环判断吗?请高手解答,谢谢

------解决方案--------------------
SQL code
select * from t
    where ABS(DATEDIFF(DAY,A_Date, B_Date))>30
        and ABS(DATEDIFF(DAY,B_Date, C_Date))>30
        and ABS(DATEDIFF(DAY,A_Date, C_Date))>30

------解决方案--------------------
-->测试数据

DECLARE @tab table(ID INT IDENTITY(1,1), usename VARCHAR(4), A_Date DATETIME,B_Date DATETIME, C_Date DATETIME)
INSERT INTO @tab 
SELECT 'aa','2012-7-9','2012-8-15','2012-4-13' UNION ALL
SELECT 'bb','2012-7-9','2012-8-8','2012-7-23' UNION ALL
SELECT 'cc','2012-6-25','2012-9-5','2012-8-13' 

-->开始查询
SELECT *
FROM @tab
WHERE Abs(Datediff(dd,a_date,b_date)) > 30
AND Abs(Datediff(dd,b_date,c_date)) > 30
-->结果集
/*
ID username A_Date B_Date C_Date 
1 aa 2012-07-09 00:00:00.000 2012-08-15 00:00:00.000 2012-04-13 00:00:00.000
*/
------解决方案--------------------
SQL code
-->测试数据

DECLARE @tab table(ID INT IDENTITY(1,1), usename VARCHAR(4), A_Date DATETIME,B_Date DATETIME, C_Date DATETIME)
INSERT INTO @tab  
SELECT 'aa','2012-7-9','2012-8-15','2012-4-13' UNION ALL
SELECT 'bb','2012-7-9','2012-8-8','2012-7-23' UNION ALL
SELECT 'cc','2012-6-25','2012-9-5','2012-8-13'  

-->开始查询
SELECT *
FROM @tab
WHERE Abs(Datediff(dd,a_date,b_date)) > 30
  AND Abs(Datediff(dd,b_date,c_date)) > 30
-->结果集
/*
ID username A_Date B_Date C_Date  
1 aa 2012-07-09 00:00:00.000 2012-08-15 00:00:00.000 2012-04-13 00:00:00.000
*/