我对SQL比较陌生。我相信我在Oracle查询中需要多个子选择来实现我感兴趣的结果,但是我无法使查询正常工作。
我需要从“Customer”表中提取基础数据,并从第二个表“Customer_Issue”中提取其他数据。还有其他表包含我需要的其他字段,但我已成功通过连接加入/选择该数据到“客户”表
“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
答案 0 :(得分: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
对于每个customerid / service组合,它根据order by
子句枚举问题。最高的问题将是最高的service_version得到“1”。我猜这就是你想要的。
答案 1 :(得分: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
根据您的需要,可能会有一种更简单的方法。