Oracle - 如何根据另一列按列分组

时间:2013-07-09 19:13:47

标签: sql oracle

我已经整理了一个查询来列出一堆相关数据。下面是查询的简化版本以及示例输出。

SELECT DISTINCT
  A.NAME AS APP_NAME,
  REPLACE(H.ENVIRONMENT,',','/') AS HOST_ENVIRONMENT,
  S.NAME AS SERVER_NAME,
  (SELECT 
      LISTAGG(HS.NAME_1, '/') WITHIN GROUP(ORDER BY HS.NAME_1)
       FROM 
         HOST_SERVER HS
   WHERE 
      HS.NAME_2 = S.NAME
  ) AS HOST_NAMES,
  CASE
      WHEN S.LOCATION_ID IN (22,28,59) THEN 'ABC'
      WHEN S.LOCATION_ID IN (6,8,9,11,53) THEN 'DBA'
      WHEN S.LOCATION_ID IN (5,41,52,43,61) THEN 'ADFS'
      WHEN S.LOCATION_ID IN (24,27,24,34,62,63,73) THEN 'ADR'
      ELSE NULL
  END AS HOST_LOCATION
FROM
  APP A
  FULL OUTER JOIN APP_HOST AH ON A.ID = AH.ID_1
  FULL OUTER JOIN HOST H ON AH.ID_2 = H.ID
  FULL OUTER JOIN HOST_SVR HS ON H.ID = HS.ID_1
  FULL OUTER JOIN SVR S ON HS.ID_2 = S.ID
GROUP BY 
  A.NAME,
  H.ENVIRONMENT,
  S.NAME,
  H.NAME,
  S.LOCATION_ID,
  S.LOCATION
ORDER BY
  A.NAME

示例输出(未完成,遗漏了一些不重要的列):

APP_NAME        HOST_ENVIRONMENT      SERVER_NAME       HOST_NAMES
ABCD            Production            server1           host1/host2/host3
ABCD            Production            server2           host4/host5/host6
ABCD            Development           server1           host1/host2/host3
ABCD            UBD                   server2           host4/host5/host6

我想要完成的是基本上按照环境对APP_NAME进行分组。我想要一条生产线和一条生产线(只需称为开发就可以了)。以下是我想要的一个例子:

APP_NAME    HOST_ENVIRONMENT   SERVER_NAME       HOST_NAMES
ABCD        Production         server1/server2   host1/host2/host3/host4/host5/host6            
ABCD        Development        server1/server2   host1/host2/host3/host4/host5/host6       

如何通过环境对这些应用程序进行分组?显然这是一个非常简化的版本,但我正在处理数千行。谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

请参阅以下查询,可能对您有用:

CREATE TABLE test(
  APP_NAME         VARCHAR2(100),
  HOST_ENVIRONMENT VARCHAR2(100),
  SERVER_NAME      VARCHAR2(100),
  HOST_NAMES       VARCHAR2(100)
  );

INSERT INTO test VALUES('ABCD','Production','server1','host1/host2/host3');
INSERT INTO test VALUES('ABCD','Production','server2','host4/host5/host6');
INSERT INTO test VALUES('ABCD','Development','server1','host1/host2/host3');
INSERT INTO test VALUES('ABCD','UBD','server2','host4/host5/host6');

/* CHECK THIS QUERY */
SELECT APP_NAME,HOST_ENVIRONMENT,
listagg(SERVER_NAME,'/' ) WITHIN GROUP (ORDER BY SERVER_NAME) AS SERVER_NAME,
listagg(HOST_NAMES,'/' ) WITHIN GROUP (ORDER BY HOST_NAMES) AS HOST_NAMES
FROM test
GROUP BY APP_NAME,HOST_ENVIRONMENT

试试这个,请看 link

注意:这是分组和concatenacion问题的解决方案,而不是问题的完整解决方案,您必须发布更多信息(例如,表格,数据等)。

我知道这不是一个好的解决方案,但你可以用你的查询替换我的表TEST,我想你会得到你需要的东西。

答案 1 :(得分:0)

您可以按多列进行分组,例如按app_name,host_environment分组,然后使用listagg聚合函数将server_names组合成单个字符串。您的数据未显示您希望如何处理app_name列中的多个值。