SQL - 仅限第一条记录

时间:2016-05-03 11:05:04

标签: sql sql-server stored-procedures

我在存储过程中有以下代码段:

where
((Question = 'SurgicalSectionCompleted' and ChangeTo = 'True') or
(Question = 'MedicalSectionCompleted' and ChangeTo = 'True'))

但是,有时在相关表格中,会有多个条目,其中ChangeTo将为true。至关重要的是,我只根据ChangeTo为True的FIRST记录进行计算。我可以使用哪些SQL命令来执行此操作?有任何想法吗?感谢。

表中记录的字段是:id,name,personNo,entryTime,question,changeFrom,ChangeTo

2 个答案:

答案 0 :(得分:10)

如果只想返回一行,请使用TOP 1。首先,使用ORDER BY

select top 1 t.*
from t
where Question in ('SurgicalSectionCompleted', 'MedicalSectionCompleted') and 
      ChangeTo = 'True'
order by entryTime asc;

如果您想要每个人的第一个,请使用row_number()

select t.*
from (select t.*,
             row_number() over (partition by personNo order by entryTime) as seqnum
      from t
      where Question in ('SurgicalSectionCompleted', 'MedicalSectionCompleted') and 
            ChangeTo = 'True'
     ) t
where seqnum = 1;

答案 1 :(得分:1)

使用TOP 1

select TOP 1 *
from table1
where
((Question = 'SurgicalSectionCompleted' and ChangeTo = 'True') or
(Question = 'MedicalSectionCompleted' and ChangeTo = 'True'))
order by <col1>