Reputation: 11
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
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
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