Performing an operation on the result of a query, without saving a table

江枫思渺然 提交于 2020-03-04 18:35:30

问题


I'm very new to SQL and T-SQL, so please forgive any mistakes in terminology or if the answer is obvious - I don't even know where to start googling for the solution to this problem.

I only have SELECT permission on a T-SQL server. I have a query that pulls a bunch of information based on an event with a Start Date (DATETIME) and End Date (DATETIME). I want to have a calculated column in my query result that indicates whether the person was just involved in back-to-back events.

So, something like this, with "Back2Back" being the desired column:

PersonID    LastName    StartDate                EndDate                    Back2Back
006         Trevelyan   2019-12-01 09:30:00.000  2019-12-02 06:15:00.000    No
007         Bond        2019-12-01 12:15:00.000  2019-12-01 12:16:00.000    No
006         Trevelyan   2019-12-02 06:15:00.000  2019-12-02 15:15:00.000    Yes

The ORDER BY will be by StartDate, if that helps or hinders at all.


回答1:


You can use the LAG function to get the end time of each person's previous event and compare that to the start time for the current event.

SELECT
  *
 ,CASE
    WHEN StartDate = LAG(EndDate) OVER (PARTITION BY PersonID ORDER BY StartDate)
      THEN 'Yes'
    ELSE 'No'
  END AS Back2Back
FROM
  @mytable
ORDER BY
  StartDate;

Results:

+----------+-----------+-------------------------+-------------------------+-----------+
| PersonID | LastName  |        StartDate        |         EndDate         | Back2Back |
+----------+-----------+-------------------------+-------------------------+-----------+
|        6 | Trevelyan | 2019-12-01 09:30:00.000 | 2019-12-02 06:15:00.000 | No        |
|        7 | Bond      | 2019-12-01 12:15:00.000 | 2019-12-01 12:16:00.000 | No        |
|        6 | Trevelyan | 2019-12-02 06:15:00.000 | 2019-12-02 15:15:00.000 | Yes       |
+----------+-----------+-------------------------+-------------------------+-----------+

This assumes that "back to back" is pretty literal. If you wanted to build some fluff time into that, you could use a DATEDIFF comparison instead of a straight equality.



来源:https://stackoverflow.com/questions/59459397/performing-an-operation-on-the-result-of-a-query-without-saving-a-table

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