Need help in the view script to get the last ward or row - depending on the sequence .

ASHMITP 141 Reputation points
2022-11-16T03:58:40.14+00:00

Hi there,

I hv a table , containing data of patient details with ward information and ward seq number.
My requirement is to get the last ward from that view.

Getting the first and second ward . How to get the last ward (TRAN LOUNGE RNS ASB) from this view.?

View script :

WITH CTE as (
SELECT DISTINCT [RESPONSIBLE_OSP_HEALTH_ORG_FULL_NAME]
,[SE_WARD_KEY]
,[SE_CBK_SK]
,[SE_REC_ID]
,[SERVICE_ENC_REC_ID]
,[HEALTH_SERVICE_WARD_NAME] as FIRST_WARD
,isnull(WARD_LOS_MIN,-1) as FIRST_WARD_LOS_MIN
,isnull(LEAD([HEALTH_SERVICE_WARD_NAME],1) OVER (PARTITION BY [SERVICE_ENC_REC_ID] ORDER BY [SE_WARD_SEQ] ASC),'-1') as SECOND_WARD
,isnull(LEAD(WARD_LOS_MIN,1) OVER (PARTITION BY [SERVICE_ENC_REC_ID] ORDER BY [SE_WARD_SEQ] ASC),-1) as SECOND_WARD_WARD_LOS_MIN
,[SE_WARD_SEQ]
FROM table
WHERE SE_WARD_SEQ in (-1,1,2)
)
SELECT * from CTE
WHERE SE_WARD_SEQ in (-1,1)

260754-image.png

strong text

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,552 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. CosmogHong-MSFT 22,781 Reputation points Microsoft Vendor
    2022-11-16T06:01:14.543+00:00

    Hi @ASHMITP
    Try this:

    WITH CTE as (  
    SELECT DISTINCT [RESPONSIBLE_OSP_HEALTH_ORG_FULL_NAME]  
    ,[SE_WARD_KEY]  
    ,[SE_CBK_SK]  
    ,[SE_REC_ID]  
    ,[SERVICE_ENC_REC_ID]  
    ,[HEALTH_SERVICE_WARD_NAME] as FIRST_WARD  
    ,isnull(WARD_LOS_MIN,-1) as FIRST_WARD_LOS_MIN  
    ,isnull(LEAD([HEALTH_SERVICE_WARD_NAME],1) OVER (PARTITION BY [SERVICE_ENC_REC_ID] ORDER BY [SE_WARD_SEQ] ASC),'-1') as SECOND_WARD  
    ,isnull(LEAD(WARD_LOS_MIN,1) OVER (PARTITION BY [SERVICE_ENC_REC_ID] ORDER BY [SE_WARD_SEQ] ASC),-1) as SECOND_WARD_WARD_LOS_MIN  
    ,C.LAST_WARD  
    ,C.LAST_WARD_LOS_MIN  
    ,[SE_WARD_SEQ]  
    FROM table T CROSS APPLY (SELECT TOP(1)[HEALTH_SERVICE_WARD_NAME] AS LAST_WARD,  
                                           [WARD_LOS_MIN] AS LAST_WARD_LOS_MIN   
    						  FROM table ORDER BY [SE_WARD_SEQ] DESC)C  
    WHERE SE_WARD_SEQ in (-1,1,2)  
    )  
    SELECT * from CTE  
    WHERE SE_WARD_SEQ in (-1,1)  
    

    Best regards,
    LiHong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments