2013-03-28 66 views
1
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 

輸出:SQL Server 2008 R2的查詢需要指導

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 

我不想在輸出負值,但還是給它像高度和工資的條件之一是令人滿意的,但萬一他們失敗的年齡。所以一個失敗,不想在o/p中顯示他們請幫助我。

回答

1

它在子查詢中如何呢?

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 
0

只是你的case語句添加到您的where子句:

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