我尝试执行以下查询:
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'”
有谁知道如何修复上面的查询?
答案 0 :(得分: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
答案 1 :(得分:5)
您不能在WHERE
子句中使用别名。您需要重复整个表达式(CAST(t1.[total_event_duration] AS DECIMAL))/(CAST (t2.[total_events_duration] AS DECIMAL)>0.02
)。
答案 2 :(得分:3)
您不能在where
,group by
或having
子句中使用别名。您可以通过将其包装在子查询中来解决这个问题:
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
否则你将不得不再次输入整件事,这是不好的。
答案 3 :(得分: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