我有一个结构表
CUSTOMER_ID INTEGER
QUOTE_ID INTEGER
VALIDFROM DATE
客户可以有多个报价。我需要获取每个客户的VALIDFROM DATE为MAX的报价ID列表。下面的查询返回按客户分组的报价列表和MAX VALIDFROM DATE,但如何查找此记录的QUOTE_ID?在group子句中包含QUOTE_ID会产生错误的结果
SELECT q.custid, max(q.validfrom)
FROM QUOTE Q
GROUP
BY q.CUSTID
请帮忙!
答案 0 :(得分:1)
希望有所帮助:
SELECT q.*
FROM quote q
JOIN(SELECT q.custid, max(q.validfrom)
FROM quote q
GROUP
BY q.custid
) P
ON q.custid = p.custid
AND q.validfrom = p.validfrom;
答案 1 :(得分:-2)
您不需要在QUOTE_ID
条款中加入GROUP BY
。只需这样做:
SELECT CUSTOMER_ID, QUOTE_ID, MAX(VALIDFROM)
FROM QUOTE
GROUP BY CUSTOMER_ID
或者,如果您只需要按客户分组QUOTE_ID
,那么您可以使用HAVING
子句:
SELECT QUOTE_ID
FROM QUOTE
GROUP BY CUSTOMER_ID
HAVING MAX(VALIDFROM)
编辑 - 1:
正如a_horse_with_no_name指出的那样,我已通过以下方式更改了我的查询:
SELECT CUSTOMER_ID, QUOTE_ID, MAX(VALIDFROM)
FROM QUOTE
GROUP BY CUSTOMER_ID, QUOTE_ID