日期:2014-05-18  浏览次数:20492 次

not exists 求解。很迷惑,不知道他是怎么执行的。。。。谢谢!
create   table   SendTime(号码   int,发送时间   Datetime)

  Insert   SendTime   Select   1381, '2007-08-02   17:51:00.000 '
      Union   ALl   Select   1381, '2007-08-02   18:26:00.000 '        
      Union   ALl   Select   1382, '2007-08-02   19:31:00.000 '
      Union   ALl   Select   1381, '2007-08-03   11:21:00.000 '

求每个号码每天发送时间最晚的记录

Select   *   From   SendTime   A   Where   Not   Exists
                (Select   1   From   SendTime   Where   号码=A.号码   And  
                                    Convert(Varchar(10),发送时间,120)=Convert(Varchar(10),A.发送时间,120)   And  
                                    发送时间> A.发送时间)
                  Order   By   号码,发送时间

结果:
1381 2007-08-02   18:26:00.000
1381 2007-08-03   11:21:00.000
1382 2007-08-02   19:31:00.000

请大家给我一步一步解释一下上边这条语句的执行过程吧!为什么是   select   1呢?
看了帮助还是不清楚啊!


------解决方案--------------------
Select * From SendTime A Where Not Exists
(Select 1 From SendTime Where 号码=A.号码 And
Convert(Varchar(10),发送时间,120)=Convert(Varchar(10),A.发送时间,120) And
发送时间> A.发送时间)
Order By 号码,发送时间

--------------------
這裡是逐條判斷的。

首先第一條數據,看看SendTime表中,有沒有号码和當前數據相同,並且是今天的數據,時間比當前數據時間大的,有。

這時,就不滿足Not Exists這個條件,所以第一條去掉。

然後第二條,SendTime表中沒有号码和當前數據相同,並且是今天的數據,時間比當前數據時間大的數據。

就滿足Not Exists這個條件,所以這一條保留。

以下類似.
------解决方案--------------------
--这样写不是更简单些吗?
declare @table table (号码 int,发送时间 Datetime)

Insert @table Select 1381, '2007-08-02 17:51:00.000 '
Union ALl Select 1381, '2007-08-02 18:26:00.000 '
Union ALl Select 1382, '2007-08-02 19:31:00.000 '
Union ALl Select 1381, '2007-08-03 11:21:00.000 '

SELECT 号码,CONVERT(VARCHAR(10),发送时间,102) AS 发送日期,max(发送时间)AS 发送时间
FROM @table GROUP BY 号码,CONVERT(VARCHAR(10),发送时间,102)