2016-11-16 123 views
0

我試着在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 

任何關於我在這裏做了什麼錯誤的指針?

謝謝!

回答

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) 
+0

謝謝Esperento57。我添加了'as'以使maxsendTS_A和B和查詢起作用。 – Ganesh

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); 
+0

謝謝戈登·利諾夫。我必須將A.SENT_TS,B.SENT_TS作爲max(A.SENT_TS)和max(B.SENT_TS)並且查詢起作用。 – Ganesh

+0

@Ganesh。 。 。是的。 。 。當我回答時,我甚至沒有看到「選擇」。 –

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