select * from tbl a where 日期=(
  Select top 1 日期 from tbl 
  where ID=a.ID and 卡号=a.卡号 order by 日期)
union 
select * from tbl a where 日期=(
  Select top 1 日期 from tbl 
  where ID=a.ID and 卡号=a.卡号 order by 日期 desc)
order by ID,卡号,日期

解决方案 »

  1.   

    select * from tbl a where 日期=(
      Select top 1 日期 from tbl 
      where ID=a.ID and 卡号=a.卡号 and datepart(hh,日期) between 6 and 8 order by 日期)
    union 
    select * from tbl a where 日期=(
      Select top 1 日期 from tbl 
      where ID=a.ID and 卡号=a.卡号 order by 日期 desc)
    order by ID,卡号,日期
      

  2.   

    奇怪,问题数据怎么挤在一起呢,原始问题是
    ID        卡号                       日期            机器号
    2 00011 2006-03-01 06:35:00.000 03
    2 00011 2006-03-01 07:39:00.000 03
    2 00011 2006-03-01 07:55:00.000 03
    2 00011 2006-03-01 18:16:00.000 03 2 00011 2006-03-02 05:55:00.000 03
    2 00011 2006-03-02 06:23:00.000 03
    2 00011 2006-03-02 07:35:00.000 03
    2 00011 2006-03-02 12:05:00.000 03
    2 00011 2006-03-02 17:54:00.000 03 2 00011 2006-03-03 05:29:00.000 03
    2 00011 2006-03-03 08:01:00.000 03
    2 00011 2006-03-03 12:03:00.000 03
    2 00011 2006-03-03 18:30:00.000 03 要得到效果是:这些是三天的记录,我的要求是取出这个ID号的每天第一条和最后一条记录,但有一个限制,
    就是每天的第一条记录必须是早上6:00到8:00的一条记录,如果6:00至8:00有多条记录,那么取距
    6:00最近的那个记录,如果这段时间没有记录,那么取8:00最近的一条记录!我要得到最终的结果是
    ID        卡号                   日期                 考勤机号
    20       0011               2006-03-01 06:35:00.000     03
    20       0011               2006-03-01 18:16:00.000     0320       0011               2006-03-02 06:23:00.000     03
    20       0011               2006-03-02 17:54:00.000     0320       0011               2006-03-03 08:01:00.000     03
    20       0011               2006-03-03 18:30:00.000     03