WHERE子句中的SQL Server结果列

时间:2011-02-01 10:47:10

标签: sql-server

SELECT 
   MyColumn = 'something'
FROM table
WHERE MyColumn == 'something'

可以在WHERE子句中使用MyColumn吗?

编辑:

以下是完整查询:

select TOP 10               
    PremiumYTDCurrent=Sum(CASE WHEN 
    AASI.Inv_Acctcur>='201101'
    and AASI.Inv_Acctcur<='201102'
    THEN (AASI.Inv_Premium)*R.[Percent]
    ELSE 0 END),

    PremiumYTDPrevious=Sum(CASE WHEN 
    AASI.Inv_Acctcur>='201001'
    and AASI.Inv_Acctcur<='201002'
    THEN (AASI.Inv_Premium)*R.[Percent]
    ELSE 0 END),  

    R.STAFF, L.Description, L.LINE_OF_BUSINESS

from AAS_Invoice AASI,Invoice I,Revenue_Tracking R,  Policy P, Line_Of_Business L
where I.Invoice_No=convert(Char,Convert(int,AASI.Inv_Entry_Num))
and I.Invoice=R.Invoice
and I.POLICY=P.POLICY
and L.LINE_OF_BUSINESS=P.LINE_OF_BUSINESS
and R.Organization IN (SELECT ST.ORGANIZATION FROM Staff ST WHERE ST.STAFF=14407)
and R.Staff=14407
and R.Activity_type='Broker'
and R.[Percent]>0

and PremiumYTDCurrent != 0

group by R.STAFF, L.Description, L.LINE_OF_BUSINESS
order by PremiumYTDCurrent DESC, PremiumYTDPrevious DESC, average_policy DESC

2 个答案:

答案 0 :(得分:1)

您不能在where子句中使用该列。请改用表达式。

and Sum(CASE WHEN 
    AASI.Inv_Acctcur>='201101'
    and AASI.Inv_Acctcur<='201102'
    THEN (AASI.Inv_Premium)*R.[Percent]
    ELSE 0 END) <> 0

修改1 没有注意到SUM条款。 尝试在订购后将其添加为HAVING子句。

having Sum(CASE WHEN 
    AASI.Inv_Acctcur>='201101'
    and AASI.Inv_Acctcur<='201102'
    THEN (AASI.Inv_Premium)*R.[Percent]
    ELSE 0 END) != 0

答案 1 :(得分:0)

您可以将SQL包装在嵌套语句中,这是一个非常简单的例子,例如:

SELECT MyMadeUpColumnName, col2, AnotherMadeUpColumn FROM (
    SELECT SUM(sillycolumn) AS 'MyMadeUpColumnName', col2 FROM table GROUP BY col2
) AS t
WHERE t.AnotherMadeUpColumn <> 0

您在派生表中(重新)定义的任何列名都将成为父选择的实际列名。