Select top 1 field with same table

Udal Bharti 0 Reputation points
2024-10-30T10:52:47.9466667+00:00

I have written this query but its executing very slow, We have 8000 of rows and this query takes almost 10 mins to execute. If anyone can help with this query optimization will be grateful.

SELECT v.iID_Event_People, CASE

  WHEN v.sOutlookEventID IS NOT NULL AND v.sOutlookEventID != '' THEN v.sOutlookEventID

  ELSE (

      SELECT TOP 1 sOutlookEventID 

      FROM dbo.Events 

       WHERE sGroupingID = v.sGroupingID AND sOutlookEventID IS NOT NULL AND sOutlookEventID != ''

   )

END AS sOutlookEventID  

FROM     dbo.Events AS v  
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,060 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,661 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Rodger Kong 360 Reputation points
    2024-10-30T14:05:53.15+00:00

    Try this code

    SELECT 
    	v.iID_Event_People, 
    	IIF(v.sOutlookEventID IS NOT NULL AND v.sOutlookEventID != '', v.sOutlookEventID, N.sOutlookEventID) AS sOutlookEventID
    FROM [#events] AS v
    LEFT JOIN
    (
    	SELECT MIN(sOutlookEventID) AS sOutlookEventID, sGroupingID FROM [#events]
    	WHERE sOutlookEventID IS NOT NULL AND sOutlookEventID != ''
    	GROUP BY sGroupingID
    )N
    ON v.sGroupingID = N.sGroupingID
    
    

    And you'b better add a nonclustered index on sGroupingID and sOutlookEventID

    0 comments No comments

  2. LiHongMSFT-4306 28,576 Reputation points
    2024-10-31T01:56:17.5833333+00:00

    Hi @Udal Bharti

    How about this query:

    SELECT iID_Event_People
    	  ,CASE WHEN sOutlookEventID IS NULL OR sOutlookEventID = ''
    	        THEN MAX(sOutlookEventID)OVER(PARTITION BY sGroupingID) 
    	        ELSE sOutlookEventID END AS sOutlookEventID
    FROM dbo.Events
    

    Best regards,

    Cosmog


    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".

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.