tags:

views:

63

answers:

4
+4  Q: 

SELECT AS problem

Hi,

I tried to perform the following query:

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

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

Does anyone know how to fix the query above?

+3  A: 

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.

Ian Henry
You *can* in an ORDER BY...
gbn
As far as I remember aliases are ok in `ORDER BY`.
a1ex07
You are correct. Edited with more accurate information.
Ian Henry
You can use aliases in HAVING as well.
CodeTwice
+5  A: 

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).

a1ex07
+2  A: 

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
rosscj2533
+6  A: 
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
gbn
+1 for a universally-applicable quick fix.
egrunin
+1 Would this have a performance hit compared to repeating the the whole expression?
Patrick
@Patrick: no, in this case it's effectively short circuited
gbn
Thank you for such clear answer!
niko