如何在使用join和groupBY时获取Oracle SQL中的最新值

时间:2018-06-17 16:28:34

标签: mysql

SELECT A.CreateDatetime,B.OrderNumber from WORKORDER A 
join UPGD B on A.phonenumber=B.number 
where B.ACCOUNTNUMBER in 
(select ACCOUNTNUMBER,CreateDatetime 
 from UPGD group BY ACCOUNTNUMBER, CreateDatetime 
HAVING COUNT(ACCOUNTNUMBER)=1 
ORDER BY CreateDatetime desc)
and ROWNUM='1'
order by A.CreateDatetime desc;

表:WORKORDER

---------------------------------------------
CreateDatetime    ACCOUNTNUMBER    phonenumber
6/17/2018           12345678        3423423534
6/16/2018           87655432        1232412344
5/20/2018           84534523        3424234234

表:UPGD

---------------------------------------------
CreateDatetime    ACCOUNTNUMBER    phonenumber
6/17/2018           12345678        3423423534
6/17/2018           12345678        3423423534
6/16/2018           87655432        1232412344
5/20/2018           84534523        3424234234

我正在尝试加入两个表并获取只有1个帐号的字段,并且只想要最新的字段

当我使用上述查询时,我收到以下错误

ORA-00907: missing right parenthesis
00907. 00000 -  "missing right parenthesis"
*Cause:    
*Action:

1 个答案:

答案 0 :(得分:0)

在SQL查询中 你的第一个错误是加入第二个条件

因为 B.ACCOUNTNUMBER 应检查一列而非两列

为什么不使用where子句而不是condtions

    SELECT A.CreateDatetime,B.OrderNumber from WORKORDER as A 
    join UPGD B on A.phonenumber=B.number 
    where B.ACCOUNTNUMBER in 
                     (select ACCOUNTNUMBER from UPGD group BY ACCOUNTNUMBER,CreateDatetime
                            HAVING COUNT(ACCOUNTNUMBER) = 1 
                                            ORDER BY CreateDatetime desc)
    and ROWNUM='1'
    order by A.CreateDatetime desc;