如何使用聚合函数进行比较

时间:2016-11-16 03:00:06

标签: sql db2

我试图在DB2中运行此查询:

SELECT  A.EMAIL_ADDR_ID, A.SENT_TS, B.SENT_TS FROM ecom.EMAIL_HIST A 
INNER JOIN ecom.EMAIL_RTM_HIST B
ON A.EMAIL_ADDR_ID = B.EMAIL_ADDR_ID
WHERE max(b.SENT_TS) > max(a.SENT_TS)
GROUP BY A.EMAIL_ADDR_ID;

在尝试运行上述查询时,我收到以下错误消息。

SQL Error [42903]: Invalid use of an aggregate function or OLAP function..SQLCODE=-120, SQLSTATE=42903, DRIVER=3.64.114

关于我在这里做了什么错误的任何指示?

谢谢!

3 个答案:

答案 0 :(得分:0)

您需要having子句:

SELECT A.EMAIL_ADDR_ID, MAX(A.SENT_TS), MAX(B.SENT_TS)
FROM ecom.EMAIL_HIST A INNER JOIN 
     ecom.EMAIL_RTM_HIST B
     ON A.EMAIL_ADDR_ID = B.EMAIL_ADDR_ID
GROUP BY A.EMAIL_ADDR_ID
HAVING max(b.SENT_TS) > max(a.SENT_TS);

答案 1 :(得分:0)

解决方案2

像这样修改您的查询

select * from (
SELECT  A.EMAIL_ADDR_ID, max(A.SENT_TS) maxsendTS_A, max(B.SENT_TS) maxsendTS_B
FROM ecom.EMAIL_HIST A INNER JOIN ecom.EMAIL_RTM_HIST B
ON A.EMAIL_ADDR_ID = B.EMAIL_ADDR_ID
GROUP BY A.EMAIL_ADDR_ID
) tmp where maxsendTS_B>maxsendTS_A

答案 2 :(得分:0)

解决方案1 ​​

SELECT  A.EMAIL_ADDR_ID, max(A.SENT_TS) maxsendTS_A, max(B.SENT_TS) maxsendTS_B
FROM ecom.EMAIL_HIST A INNER JOIN ecom.EMAIL_RTM_HIST B
ON A.EMAIL_ADDR_ID = B.EMAIL_ADDR_ID
GROUP BY A.EMAIL_ADDR_ID
having max(b.SENT_TS) > max(a.SENT_TS)