Conditional where statement in T-SQL

不羁的心 提交于 2019-12-23 12:06:09

问题


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.


回答1:


Try this:

    SELECT EmergencyAttendanceId


    case when count(EmergencyAttendanceId) > 1 then
          MIN
          (
          case when TriageDateTime is null then SourceCreateDateTime end 
          ) 
    else
          min(SourceCreateDateTime)
    end as max_date


    FROM FactEmergencyAttendanceTriageDetail 
    GROUP BY EmergencyAttendanceId 



回答2:


Use CASE in place of your pseudo-code:

WHERE TriageEndDateTime = 
    CASE WHEN EmergencyAttendanceId > 1 THEN NULL ELSE NOT NULL END


来源:https://stackoverflow.com/questions/4495974/conditional-where-statement-in-t-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!