2010-10-22 73 views
4

我試着進行下面的查詢:SELECT AS問題

SELECT t1.[user1], t1.[user2], 
    (CAST(t1.[total_event_duration] AS DECIMAL))/(CAST (t2.[total_events_duration] AS DECIMAL)) AS buddy_strength 
FROM [CDRs].[dbo].[aggregate_monthly_events] AS t1 
INNER JOIN [CDRs].[dbo].[user_monthly_stats] AS t2 
    ON t1.[user1] = t2.[user1] 
WHERE buddy_strength > 0.02 

但它返回一個錯誤「無效的列名稱buddy_strength'」

有誰知道如何解決上面的查詢?

回答

7
SELECT * 
FROM 
    (
    SELECT 
     t1.[user1], t1.[user2],(CAST(t1.[total_event_duration] AS DECIMAL))/(CAST (t2.[total_events_duration] AS DECIMAL)) AS buddy_strength 
     FROM [CDRs].[dbo].[aggregate_monthly_events] AS t1 
      INNER JOIN [CDRs].[dbo].[user_monthly_stats] AS t2 
       ON t1.[user1] = t2.[user1] 


    ) foo 
     WHERE foo.buddy_strength > 0.02 
+0

適用於普遍適用的快速修復。 – egrunin 2010-10-22 13:47:37

+0

+1與重複整個表達式相比,這會有性能優勢嗎? – Patrick 2010-10-22 14:17:45

+0

@帕特里克:不,在這種情況下,它是有效的短路 – gbn 2010-10-22 16:51:49

3

您不能在where,group byhaving子句中使用別名。您可以通過在一個子查詢包裹它解決這個問題:

SELECT * FROM (
    SELECT 
     t1.[user1], 
     t1.[user2], 
     (CAST(t1.[total_event_duration] AS DECIMAL)) 
      /(CAST (t2.[total_events_duration] AS DECIMAL)) 
      AS buddy_strength 
    FROM [CDRs].[dbo].[aggregate_monthly_events] AS t1 
    INNER JOIN [CDRs].[dbo].[user_monthly_stats] AS t2 ON t1.[user1] = t2.[user1] 
) a 
WHERE a.buddy_strength > 0.02 

否則,你將不得不再次進行鍵入整個事情,這是沒有好處的。

+1

*您可以*在ORDER BY ... – gbn 2010-10-22 13:45:17

+0

至於我記得別名在'ORDER BY'中確定。 – a1ex07 2010-10-22 13:45:33

+0

你是對的。用更準確的信息編輯。 – 2010-10-22 13:50:36

5

您不能在WHERE子句中使用別名。你需要重複整個表達式(CAST(t1.[total_event_duration] AS DECIMAL))/(CAST (t2.[total_events_duration] AS DECIMAL)>0.02)。

2

您不能在where子句中使用別名列。我認爲你必須要重現導出字段的值在where子句中,像這樣的:

SELECT t1.[user1], t1.[user2],(CAST(t1.[total_event_duration] AS DECIMAL))/(CAST (t2.[total_events_duration] AS DECIMAL)) AS buddy_strength 
    FROM [CDRs].[dbo].[aggregate_monthly_events] AS t1 
     INNER JOIN [CDRs].[dbo].[user_monthly_stats] AS t2 
      ON t1.[user1] = t2.[user1] 
    WHERE (CAST(t1.[total_event_duration] AS DECIMAL))/(CAST (t2.[total_events_duration] AS DECIMAL)) > 0.02