【问题标题】:How to concatenate rows in one field in oracle, with a query over mutliple tables如何在oracle中连接一个字段中的行,并查询多个表
【发布时间】:2018-08-10 13:48:15
【问题描述】:

这是在 oracle 数据库中。因此使用 listagg....

我有一个客户表和一个资产表。我需要能够返回资产表中以逗号分隔的 IP 地址。每个客户可以有 2 到 30 个(左右)IP。

资产

cust_id   IP
ABCD      192.168.1.5
ABCD      192.168.1.6
ABCD      192.168.1.7
DEFG      192.168.10.1
DEFG      192.168.10.2

客户

Cust_id    Cust_name
DEFG       My first customer
ABCD       My second Customer

我需要退货:

My First Customer    DEFG    192.168.10.1, 192.168.10.2
My second customer   ABCD    192.168.1.5, 192.168.1.6, 192.168.1.7

一个简单的连接查询可以很好地返回单个行:

select  
CUST_NAMES.CUST_ID as CUST_ID, CUST_NAMES.CUST_NAME, IP
 from CUST_NAMES
INNER JOIN ASSETS 
ON CUST_NAMES.CUST_ID = ASSETS.CUST_ID

listagg 在单个表查询上运行良好:

select ASSETS.CUST_ID, listagg(IP, ',') within group (order by ASSETS.CUST_ID) 
from ASSETS
INNER JOIN CUSTOMERS
ON CUSTOMERS.CUST_ID = ASSETS.CUST_ID
group by ASSETS.CUST_ID

但是,当我尝试将客户名称添加到查询中时,它告诉我这不是 GROUP BY 函数

select CUSTOMERS.CUST_NAME, ASSETS.CUST_ID, listagg(IP, ',') within group (order by ASSETS.CUST_ID)
from ASSETS
INNER JOIN CUSTOMERS
ON CUSTOMERS.CUST_ID = ASSETS.CUST_ID
group by ASSETS.CUST_ID

【问题讨论】:

  • @Alex, .... 我希望你听到我额头上的 SLAP .....

标签: oracle join listagg


【解决方案1】:

选择列表中的所有非聚合列都必须包含在group by 子句中,因此您也需要将CUSTOMERS.CUST_NAME 添加到该子句中。

select CUSTOMERS.CUST_NAME, ASSETS.CUST_ID,
  listagg(IP, ',') within group (order by ASSETS.CUST_ID)
from ASSETS
INNER JOIN CUSTOMERS
ON CUSTOMERS.CUST_ID = ASSETS.CUST_ID
group by CUSTOMERS.CUST_NAME, ASSETS.CUST_ID

这实际上与涉及两个表无关。

【讨论】:

    【解决方案2】:

    由于每个客户 ID 只有一个客户(姓名)(我猜),我认为没有理由不简单地将 CUST_NAME 添加到您的 GROUP BY:

    select CUSTOMERS.CUST_NAME, ASSETS.CUST_ID, listagg(IP, ',') within group (order by ASSETS.CUST_ID)
     from ASSETS
    INNER JOIN CUSTOMERS ON CUSTOMERS.CUST_ID = ASSETS.CUST_ID
    group by ASSETS.CUST_ID, CUSTOMERS.CUST_NAME
    

    【讨论】:

      猜你喜欢
      • 2020-08-07
      • 1970-01-01
      • 2011-01-21
      • 1970-01-01
      • 2021-01-21
      • 1970-01-01
      • 2014-06-22
      • 1970-01-01
      • 2014-02-18
      相关资源
      最近更新 更多