使用别名获取此SQL语句

时间:2011-08-18 14:52:22

标签: sql postgresql alias

我基本上想要做的是:计算属性的差异,然后获得最大差异的行。

所以,这就是我的尝试:

SELECT caller_aor, (end_time - start_time) as duration
    FROM cdrs
    GROUP BY caller_aor
    HAVING duration = (SELECT MAX(end_time - start_time) FROM cdrs);

HAVING子句中的持续时间给出了错误,但我无法弄清楚我必须在那里做什么。

非常感谢帮助。

3 个答案:

答案 0 :(得分:3)

您不希望GROUP BYHAVING(仅在聚合列时使用它们。)

你想要一个简单的WHERE

SELECT caller_aor, (end_time - start_time) as duration
FROM cdrs
WHERE (end_time - start_time) = (SELECT MAX(end_time - start_time) FROM cdrs);

答案 1 :(得分:2)

尝试此查询

SELECT top 1 caller_aor, Max(end_time - start_time) as duration
FROM cdrs
GROUP BY caller_aor
Order by duration

答案 2 :(得分:1)

另一种看待这种情况的方法是使用limit

SELECT caller_aor, (end_time-start_time) AS duration
FROM cdrs
ORDER BY duration DESC
LIMIT 1