T-SQL 中的条件 where 语句
我有一个表,它返回一个值的历史记录以及当前值,每个值都有一个日期。
最旧的日期是主要记录。如果值发生更改,则会使用旧值创建新记录,并使用新值更新主记录。如果这种情况再次发生,则会创建第三条记录,其中包含现在的旧值。
因此,如果值从 4 开始,更改为 2,然后再次更改为 1。记录将继续
1
4
2
我当前正在表上创建其自身的内部联接,如下所示,它获取上述 3 条记录的最大日期,其中将为 2.. 我需要的实际值是 4。判断一条记录是否为历史记录的最简单方法是 TriageEndDateTime 为 NULL。
INNER JOIN (SELECT EmergencyAttendanceId,MIN(SourceCreateDateTime) as Max_Date
FROM FactEmergencyAttendanceTriageDetail
GROUP BY EmergencyAttendanceId) AS EAiD
ON EAiD.EmergencyAttendanceId = FactEmergencyAttendanceTriageDetail.EmergencyAttendanceId
AND EAiD.Max_Date = FactEmergencyAttendanceTriageDetail.SourceCreateDateTime
我需要做的是选择第二条记录,但前提是它存在。所以类似这样的事情。
SELECT EmergencyAttendanceId,MIN(SourceCreateDateTime) as Max_Date
FROM FactEmergencyAttendanceTriageDetail
WHERE IF COUNT(EmergencyAttendanceId) > 1 THEN TriageEndDateTime Is NULL ELSE NOT NULL
GROUP BY EmergencyAttendanceId
inside the INNER JOIN.
谁能帮我解决这个问题吗?
示例数据
在上述情况下,记录 2 就是我要查找的记录。
I've got a table that returns the history of a value, as well as the current one, each with a date.
The oldest date is the main record. If the value is changed, a new record is created, with the old value, and the main record is updated with the new value. If this happens again, a third record is created, which contains the now old value.
So if the value starts at 4, changes to 2, then again changes to 1. The records will go
1
4
2
I'm currently creating an inner join on the table to itself as follows, which gets the max date of the 3 above records, which would be 2.. The actual value I need is the 4. The easiest way to tell if a record is a historical one is that the TriageEndDateTime is NULL.
INNER JOIN (SELECT EmergencyAttendanceId,MIN(SourceCreateDateTime) as Max_Date
FROM FactEmergencyAttendanceTriageDetail
GROUP BY EmergencyAttendanceId) AS EAiD
ON EAiD.EmergencyAttendanceId = FactEmergencyAttendanceTriageDetail.EmergencyAttendanceId
AND EAiD.Max_Date = FactEmergencyAttendanceTriageDetail.SourceCreateDateTime
What I need to do is select the second record, but only if it exists. So something along the lines of this.
SELECT EmergencyAttendanceId,MIN(SourceCreateDateTime) as Max_Date
FROM FactEmergencyAttendanceTriageDetail
WHERE IF COUNT(EmergencyAttendanceId) > 1 THEN TriageEndDateTime Is NULL ELSE NOT NULL
GROUP BY EmergencyAttendanceId
inside the INNER JOIN.
Can anyone help me with this?
Sample data
In the above case, record 2 is the one I'm after.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
Try this:
使用
CASE
代替伪代码:Use
CASE
in place of your pseudo-code: