2

我对 SQL 比较陌生。我相信我需要在我的 Oracle 查询中进行多个子选择才能获得我感兴趣的结果,但我一直无法让查询正常工作。

我需要从“客户”表中提取基本数据,并从第二个表“客户问题”中提取附加数据。还有其他表包含我需要的其他字段,但我已通过连接到“客户”表成功地连接/选择了该数据

我需要的“Customer_Issue”数据位于“Service”、“Service_Issue”和“Service Version”字段中。每个服务有多个服务问题,每个服务问题有多个服务版本。

对于每个服务,我只需要选择最大服务问题,对于选择的服务问题,我只需要选择最大服务版本。

通过子选择,我已经能够选择最大服务问题,如下所示:

Select c.customer_id, ci.service, ci.service_issue
from customer c
left outer join CUSTOMER_issue ci on c.CUSTOMER_ID = ci.CUSTOMER_ID
join (select CUSTOMER_ID, service, max(service_ISSUE) as service_ISSUE
from CUSTOMER_issue
group by CUSTOMER_ID, service) ci1
on ci1.CUSTOMER_ID = ci.CUSTOMER_ID and ci1.service = ci.service
and ci1.service_issue = ci.service_issue

但是,我无法获得后续的子选择来获得最大服务版本。这是我尝试过的(在查询中,它直接在上面的代码下方)

join (select CUSTOMER_ID, service, service_ISSUE, max (service_VERSION) as service_VERSION
from CUSTOMER_issue
group by CUSTOMER_ID, service, service_ISSUE) ci2
on ci1.CUSTOMER_ID = ci2.CUSTOMER_ID and ci1.service = ci2.service and
ci1.service_ISSUE = ci2.service_ISSUE and ci1.service_VERSION = ci2.service_VERSION
4

2 回答 2

1

我怀疑你想要最高版本的最高版本。我不确定,但这就是我解释这个问题的方式。

如果是这样,最好的解决方案是使用row_number()

select  c.customer_id, ci.service, ci.service_issue     
from customer c left outer join
     (select ci.*,
             ROW_NUMBER() over (partition by ci.customer_id, ci.service
                                order by service_issue desc, service_version desc
                               ) as seqnum
      from CUSTOMER_issue ci
     ) ci
     on c.CUSTOMER_ID = ci.CUSTOMER_ID and
        ci.seqnum = 1

对于每个客户 ID/服务组合,它根据order by子句列举问题。最高问题的最高 service_version 将获得“1”。我的猜测是,这就是你想要的。

于 2013-02-26T15:27:37.223 回答
0

如果我了解您的要求,这样的事情应该可以解决您的子查询问题:

SELECT 
    c.customer_id, 
    ci1.service, 
    ci1.service_name, 
    ci1.service_issue, 
    ci2.service_version
FROM customer c
    JOIN (
        SELECT CUSTOMER_ID, service, service_name, max(service_ISSUE) as service_ISSUE
        FROM CUSTOMER_issue
        GROUP BY CUSTOMER_ID, service, service_name
        ) ci1 ON c.CUSTOMER_ID = ci1.CUSTOMER_ID
    JOIN  (
        SELECT CUSTOMER_ID, service, max(service_VERSION) as service_VERSION
        FROM CUSTOMER_issue
        GROUP BY CUSTOMER_ID, service
        ) ci2 ON c.CUSTOMER_ID = ci2.CUSTOMER_ID AND ci1.service = ci2.service

根据您的需要,可能有更简单的方法。

于 2013-02-26T15:31:00.327 回答