2011-02-01 116 views
0
SELECT 
    MyColumn = 'something' 
FROM table 
WHERE MyColumn == 'something' 

可能在WHERE子句中使用MyColumnWHERE子句中的SQL Server結果列

編輯:

下面是完整的查詢:

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 
+0

我不明白,只要MyColumn存在於數據庫中,你可以做上述查詢 – 2011-02-01 10:52:56

+0

這就是說,MyColumn是由用戶定義的,它不存在於db – 2011-02-01 10:55:39

回答

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 
0

你可以換的SQL了在嵌套聲明中,一個窘況簡單的例子是,如:

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

任何列名,你(重新)定義派生表成爲實際列父級選擇的名稱。