2

可能重复:
sql server 使用计算列

有没有办法做到这一点:

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?

4

2 回答 2

2

贴一个

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

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

于 2012-10-08T20:59:06.883 回答
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)
于 2012-10-08T20:59:24.693 回答