*SQL - IF Statement Equivalent* - Help much appreciated

Lee_Walmsley 121 Reputation points
2022-02-15T12:35:03.53+00:00

Good Afternoon,

I am relatively new to SQL and have come across something I can easily do in Excel but I need to replicate in SQL. I am looking back at the last 3 months of data for each individual and making an overall decision. So if any of the last 3 months contain "NEET" then it needs to return "NO". If the last 3 months contain all or a combination of "NOT NEET" or BLANK then "YES" . You can see the simple formula being used below:

174427-image.png

I have been able to group my data in SQL by month, but it is the next stage, the overall category that I am unable how to create:

174489-image.png

Any advice or guidance, would be much appreciated. Many Thanks

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

Accepted answer
  1. Viorel 117.6K Reputation points
    2022-02-15T19:38:12.507+00:00

    If you already have a table, view or subquery that contains these three columns, then try something like this:

    select *, case when [Month 1] = 'NEET' or [Month 2] = 'NEET' or [Month 3] = 'NEET' then 'NO' else 'YES' end as Target
    from MyTable
    

1 additional answer

Sort by: Most helpful
  1. LiHong-MSFT 10,051 Reputation points
    2022-02-16T06:00:36.157+00:00

    Hi @Lee_Walmsley
    If you have written the SQL to group data by month ,please refer to this :

    ;WITH CTE as  
    (  
     --Put the Sql statement that you group your data by month here  
    )  
    SELECT individual_name,[Month 1],[Month 2],[Month 3],  
           CASE WHEN [Month 1] IS NULL AND [Month 2] IS NULL AND [Month 3] IS NULL THEN 'NONE RECORDED'  
                WHEN [Month 1] = 'NEET' OR [Month 2] = 'NEET' OR [Month 3] = 'NEET' THEN 'NO' ELSE 'YES' END AS TARGET  
    FROM CTE  
    

    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.


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.