SQL Server:使用distinct关键字选择唯一的条目,但是它将返回所有列

时间:2019-02-28 04:27:16

标签: sql sql-server-2012

select distinct  
    TM.Tranaction_Slno, TM.Created_On,
    convert(varchar(10), TM.Created_On, 120) as CreatedOn,  
    TT.Read_Time,
    convert(varchar(10), TT.Read_Time, 120) as ReadTime,        
    1 as 'Trailer Count', TMM.Trailer_RegNo, TT.Location,        
    (TD.Container_Number) Container_Number, CFM.CFS_Name,        
    convert(varchar(5), DateDiff(s, TM.Created_On, TT.Read_Time) / 3600) + ':' +        
       convert(varchar(5), DateDiff(s, TM.Created_On,  TT.Read_Time) % 3600 / 60) + ':'+        
       convert(varchar(5), (DateDiff(s, TM.Created_On, TT.Read_Time) % 60))  TimeDiff,        
    convert(varchar(5), DateDiff(hour, TM.Created_On, Read_Time)) [Time]
from 
    Transaction_Master TM         
inner join 
    Transaction_Data TD on TD.Tranaction_Slno = TM.Tranaction_Slno        
left join 
    Transaction_Track TT on TT.Transaction_Slno = TM.Tranaction_Slno 
inner join 
    CFSMaster CFM on TM.CFS_ID = CFM.CFS_Id        
inner join 
    TrailerMaster TMM on TM.Trailer_ID= TMM.Trailer_ID        
where 
    TM.Created_On between '2019-02-27 00:00:00' and '2019-02-27 23:59:59' 
    and TM.Tranaction_Slno = 1770575 

我选择的条目将仅返回不重复的但不返回。屏幕截图如下所示:

enter image description here

3 个答案:

答案 0 :(得分:3)

从Container_Number列的列表中删除。 您只会得到3行。

如果您需要Container_Number信息,则可以考虑使用分组依据。

答案 1 :(得分:1)

我认为这可能会获得3行,请注意,我仅在分区中使用了位置和事务。

select * from (
select    TM.Tranaction_Slno, TM.Created_On,convert(varchar(10),TM.Created_On,120) as CreatedOn,  
TT.Read_Time,convert(varchar(10),TT.Read_Time,120) as ReadTime,        
1 as 'Trailer Count' ,TMM.Trailer_RegNo,TT.Location,        
(TD.Container_Number) Container_Number ,CFM.CFS_Name, row_number() over (partition by TM.Tranaction_Slno,TT.Location order by TM.Created_On desc) rownum           
convert(varchar(5),DateDiff(s, TM.Created_On, TT.Read_Time)/3600)+':'+        
convert(varchar(5),DateDiff(s, TM.Created_On, TT.Read_Time)%3600/60)+':'+        
convert(varchar(5),(DateDiff(s, TM.Created_On, TT.Read_Time)%60))  TimeDiff,        
convert(varchar(5),DateDiff(hour, TM.Created_On, Read_Time))  [Time]
from Transaction_Master TM         
inner join Transaction_Data TD on TD.Tranaction_Slno = TM.Tranaction_Slno        
left join Transaction_Track TT on TT.Transaction_Slno = TM.Tranaction_Slno 
inner join CFSMaster CFM on TM.CFS_ID = CFM.CFS_Id        
inner join TrailerMaster TMM on TM.Trailer_ID= TMM.Trailer_ID        
where TM.Created_On between '2019-02-27 00:00:00' and '2019-02-27 23:59:59' 
and TM.Tranaction_Slno=1770575 ) test 
where test.rownum = 1 

答案 2 :(得分:1)

在这里,只是为了说明我在评论中所说的话。

https://www.db-fiddle.com/f/5CUuAwng7ZAyVinSo36Q5f/0