user2220065
user2220065

Reputation: 11

SQL Server 2008 R2 query need guidance

SELECT 
    A.First_Name, b.First_Name, A.DOB, B.DOB, A.Token, B.Token, 
    DATEDIFF(YEAR, A.DOB, B.DOB)                        -
    (CASE
       WHEN DATEADD(YY, DATEDIFF(YEAR, A.DOB, B.DOB), A.DOB) > Getdate() 
         THEN 1                                        
         ELSE 0 END) 'Age Difference' 
FROM 
   Boys_details A , Girls_details B
WHERE
   a.Cast = 'brahmin'
   AND A.City = 'pune'
   AND a.Height >= B.Height
   AND a.Salary >= B.salary

Output:

Nilesh  Ruchita 1973-01-21  1964-12-01  9   89  -9
Nilesh  Smitha  1973-01-21  1976-07-30  9   77  3
Nilesh  Richa   1973-01-21  1974-04-21  9   2   1

I don't want minus values in output , but still its give as one of the condition like height and salary is satisfying but in case of age they failed. So one that fail in dont want to show them in o/p Please help me.

Upvotes: 1

Views: 659

Answers (2)

Jason Carter
Jason Carter

Reputation: 925

Just add your case statement to your where clause:

SELECT 
    A.First_Name, b.First_Name, A.DOB, B.DOB, A.Token, B.Token, 
    DATEDIFF(YEAR, A.DOB, B.DOB)                        -
    (CASE
       WHEN DATEADD(YY, DATEDIFF(YEAR, A.DOB, B.DOB), A.DOB) > Getdate() 
         THEN 1                                        
         ELSE 0 END) 'Age Difference' 
FROM 
  Boys_details A , Girls_details B
WHERE
   a.Cast = 'brahmin'
   AND A.City = 'pune'
   AND a.Height >= B.Height
   AND a.Salary >= B.salary
   AND (CASE WHEN DATEADD(YY, DATEDIFF(YEAR, A.DOB, B.DOB), A.DOB) > Getdate() 
     THEN 1                                        
     ELSE 0 END) => 0

Upvotes: 0

John Woo
John Woo

Reputation: 263723

how about it in a subquery?

SELECT  *
FROM
        (
            SELECT  A.First_Name,
                    b.First_Name,
                    A.DOB,
                    B.DOB,
                    A.Token,
                    B.Token, 
                    DATEDIFF(YEAR,A.DOB,B.DOB) -
                        (CASE WHEN DATEADD(YY,DATEDIFF(YEAR,A.DOB,B.DOB),A.DOB)> Getdate() 
                                THEN 1                                        
                                ELSE 0 
                        END) AS [Age Difference] 
            from    Boys_details A , 
                    Girls_details B
            where   a.Cast='brahmin' and 
                    A.City='pune' and 
                    a.Height >= B.Height and 
                    a.Salary>=B.salary
        ) s
WHERE [Age Difference] >= 0

Upvotes: 1

Related Questions