开发者

SELECT AS problem

I tried to perform the following query:

SELECT t1.[user1], t1.[user2],
    (CAS开发者_运维技巧T(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

But it returns an error "Invalid column name 'buddy_strength'"

Does anyone know how to fix the query above?


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


You cannot use aliases in WHERE clause. You need to repeat the whole expression (CAST(t1.[total_event_duration] AS DECIMAL))/(CAST (t2.[total_events_duration] AS DECIMAL)>0.02).


You can't use aliases in where, group by, or having clauses. You can get around this by wrapping it in a subquery:

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

Otherwise you'll have to type that whole thing out again, which is no good.


You cannot use an aliased column in a where clause. I think you'll have to reproduce the value of that derived field in the where clause, like this:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜