![](/img/trans.png)
[英]How to select records without duplicates with the latest record in one field in SQL?
[英]How to select one record at a time without using cursor?
我在SQL SERVER中有两个表。
DBO.VitalPatientDetails =>
| PatientDetailsId | PatientId | PatientName | 单位名称| 床名| PatientDOB | LastAlarmReceivedAt |
DBO.VitalAlarmDetails =>
| ID | PatientDetailsId(请参阅VitalPatientDetails.PatientDetailsId)| VitalGenerationTime | 文件名|
我需要检索由VitalGenerationTime升序排列的PatientDetailsId分组的DBO.VitalAlarmDetails的所有字段。 我为此编写了光标,如下所示,它正在返回多个结果集。 我需要在不使用光标的情况下将其放在单个集合中。 我只想知道我是否可以在没有光标的情况下执行此操作。
DECLARE @PatientDetailsId BIGINT
DECLARE @getAlarmDetails CURSOR
SET @getAlarmDetails = CURSOR FOR SELECT PatientDetailsId FROM VitalPatientDetails
OPEN @getAlarmDetails
FETCH NEXT FROM @getAlarmDetails INTO @PatientDetailsId
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT * FROM VitalAlarmDetails
WHERE PatientDetailsId = @PatientDetailsId
ORDER BY VitalGenerationTime ASC
FETCH NEXT FROM @getAlarmDetails INTO @PatientDetailsId
END
CLOSE @getAlarmDetails
DEALLOCATE @getAlarmDetails
谢谢。
尝试使用WHILE
循环替换CURSOR
。 我在另一个SO问题中张贴了一个示例:
它会变成如下所示:
SELECT @PatientDetailsId = MIN (PatientDetailsId) FROM VitalAlarmDetails WHILE @PatientDetailsId IS NOT NULL BEGIN ' Do stuff here SELECT @PatientDetailsId = MIN (PatientDetailsId ) FROM VitalAlarmDetails WHERE PatientDetailsId > @PatientDetailsId END
编辑:
要返回一个集合而不是逐行查找它,请使用以下方法:
SELECT
VAD.*
FROM
VitalAlarmDetails VAD JOIN
VitalPatientDetails VPD ON VAD.PatientDetailsId = VPD.PatientDetailsId
编辑2:
JOIN
仍然没有产生预期的结果。 建议在WHILE
循环内使用临时表存储结果。 这似乎奏效了。
好的,因此,如果我正确地理解了您由VitalGenerationTime排序的单个结果集(以及使用PatientDetailsId排序的光标的结果集?
怎么样
SELECT PatientDetailsId,
VitalGenerationTime
FROM VitalAlarmDetails
ORDER BY PatientDetailsId,
VitalGenerationTime
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.