SQL - WHERE子句中的派生字段

时间:2012-10-08 20:56:33

标签: sql sql-server

  

可能重复:
  sql server use computed column

有没有办法做到这一点:

select Name, 
    (SELECT Max(reference) 
        from Rematch 
        WHERE Gender='M' and convert(varchar,getdate,103) = '08/10/2012'
    ) As MaxReferenceMale, 
    (SELECT Max(reference) 
        from Rematch 
        WHERE Gender='F' and convert(varchar,getdate,103) = '08/10/2012'
    ) As MaxReferenceFemale
WHERE (Gender='M' and Reference > MaxReferenceMale) Or 
    (Gender='F' and Reference > MaxReferenceFemale)

我意识到可能有更好的方法来编写查询。是否可以在WHERE子句中引用MaxReferenceFemale和MaxReferenceMale?

2 个答案:

答案 0 :(得分:2)

坚持

SELECT * FROM (...) WHERE ...

围绕您的查询。一旦WHERE子句位于外部SELECT的内部,就可以使用别名列。

答案 1 :(得分:2)

如果要在WHERE子句中引用它们,则需要子查询:

SELECT *
FROM
(
   select Name,  Gender, Reference 
      (SELECT Max(reference) 
        from Rematch 
        WHERE Gender='M' and convert(varchar,getdate,103) = '08/10/2012') As MaxReferenceMale, 
      (SELECT Max(reference) 
        from Rematch WHERE Gender='F' and convert(varchar,getdate,103) = '08/10/2012') As MaxReferenceFemale
) x
WHERE (Gender='M' and Reference > MaxReferenceMale) 
    Or (Gender='F' and Reference > MaxReferenceFemale)

查看原始查询,看起来您在查询中缺少FROM子句,因此使用子查询语法将类似于此:

select x.name, x.MaxReferenceMale, x.MaxReferenceFemale
from rematch r
left join
(
    select Name, 
        (SELECT Max(reference) 
            from Rematch 
            WHERE Gender='M' and convert(varchar,getdate,103) = '08/10/2012'
        ) As MaxReferenceMale, 
        (SELECT Max(reference) 
            from Rematch 
            WHERE Gender='F' and convert(varchar,getdate,103) = '08/10/2012'
        ) As MaxReferenceFemale
    from rematch
) x
    on r.name = x.name
WHERE (r.Gender='M' and r.Reference > x.MaxReferenceMale) Or 
    (r.Gender='F' r.and Reference > x.MaxReferenceFemale)