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

查询时过滤部分不符合要求的数据
我现在可以查询出某时间段内某张的卡所有流水,我的sql如下:
/****** Script for SelectTopNRows command from SSMS  ******/
SELECT [CardNo]
      ,[CardID]
      ,[CardSave]
      ,[TollAmount]
      ,[ExTime]
      ,[ExRoad]
      ,[ExStation]
      ,[ExShiftDate]
      ,[EnTime]
      ,[EnRoad]
      ,[EnStation]
      ,[ExVehPlate]
      ,[VerifyCode]
      ,[DealStatus]
      ,[SendTime]
  FROM [QTKCenter].[dbo].[SpendHistory]
  where [CardNo] ='6212262409000028515' and [ExTime] between '2013-3-1' and '2013-3-31'


但是流水里面有些数据我想剔除:对于相同Extime 和ExStantion的流水,只取sendTime最大的那条数据。
想了半个小时了,暂时没想法,各位有什么好办法吗?

------解决方案--------------------
select *
from [QTKCenter].[dbo].[SpendHistory] a
where exists (select 1 from (
select max(sendtime)sendtime,extime,exstantion
from [QTKCenter].[dbo].[SpendHistory]
group by extime,exstantion)b where a.extime=b.extime and a.exstantion=b.exstantion 
and a.sendtime=b.sendtime) and [CardNo] ='6212262409000028515' and [ExTime] between '2013-3-1' and '2013-3-31'

------解决方案--------------------
select a.*
from
(SELECT [CardNo]
      ,[CardID]
      ,[CardSave]
      ,[TollAmount]
      ,[ExTime]
      ,[ExRoad]
      ,[ExStation]
      ,[ExShiftDate]
      ,[EnTime]
      ,[EnRoad]
      ,[EnStation]
      ,[ExVehPlate]
      ,[VerifyCode]
      ,[DealStatus]
      ,[SendTime]
FROM [QTKCenter].[dbo].[SpendHistory]
where [CardNo] ='6212262409000028515' and [ExTime] between '2013-3-1' and '2013-3-31'
)a
inner join 
(
SELECT Extime,ExStantion,max(sendTime) as sendTime
FROM [QTKCenter].[dbo].[SpendHistory]
where [CardNo] ='6212262409000028515' and [ExTime] between '2013-3-1' and '2013-3-31'
group by Extime,ExStantion
)b on a.Extime=b.Extime and a.ExStantion=b.ExStantion and a.sendTime=b.sendTime 

------解决方案--------------------