如何在pl-sql

时间:2015-12-07 06:42:46

标签: sql oracle

我有一个相当复杂的遗留sql查询,它为这样的文档选择属性列表:

 type |  name   | attr | int_val |  str_val 
--------------------------------------------
  1   |  doc-1  |  10  |  1003   |   null
  1   |  doc-1  |  15  |  null   |  string1
  2   |  doc-2  |  13  |  1004   |   null
  2   |  doc-2  |  22  |  null   |  string2
  1   |  doc-3  |  10  |  1005   |   null
  1   |  doc-3  |  15  |  null   |  string3

我害怕改变遗留sql中的任何内容,所以我想将现有的输出转换为:

 type |  name  | attr-A | attr-B
----------------------------------
  1   | doc-1  |  1003  | string1
  2   | doc-2  |  1004  | string2
  1   | doc-3  |  1005  | string3
  • 对于type = 1的每个文档:attr-A是attr = 10的属性(使用 int_val),attr-B是属性,attr = 15(使用str_val)
  • 对于type = 2的每个文档:attr-A是attr = 13的属性(使用int_val),attr-B是attr = 22的属性(使用str_val)

请帮我编写以我提议的方式处理现有输出的查询。

2 个答案:

答案 0 :(得分:1)

您的逻辑可以GROUP BYCASE WHEN

SELECT type, name,
    MAX(CASE WHEN type = 1 AND attr = 10 THEN int_val 
             WHEN type = 2 AND attr = 13 THEN int_val
       END) AS AttrA,
    MAX(CASE WHEN type = 1 AND attr = 15 THEN str_val 
             WHEN type = 2 AND attr = 22 THEN str_val 
       END) AS AttrB
FROM your_table
GROUP BY type, name;

LiveDemo

输出:

╔══════╦═══════╦═══════╦═════════╗
║ type ║ name  ║ attrA ║  attrB  ║
╠══════╬═══════╬═══════╬═════════╣
║    1 ║ doc-1 ║  1003 ║ string1 ║
║    2 ║ doc-2 ║  1004 ║ string2 ║
║    1 ║ doc-3 ║  1005 ║ string3 ║
╚══════╩═══════╩═══════╩═════════╝

答案 1 :(得分:1)

试试这个。它可以帮助您解决问题。如有任何问题,请告诉我。

SELECT a.typ,
  a.nme,
  MAX(a.int_val),
  MAX(a.str_val)
FROM
  (SELECT 1 AS typ,'doc-1' nme,10 attr,1003 int_val,NULL AS str_val FROM dual
  UNION ALL
  SELECT 1 AS typ,
    'doc-1' nme,
    15 attr,
    NULL int_val,
    'string1' AS str_val
  FROM dual
  UNION ALL
  SELECT 2 AS typ,'doc-2' nme,13 attr,1004 int_val,NULL AS str_val FROM dual
  UNION ALL
  SELECT 2 AS typ,
    'doc-2' nme,
    22 attr,
    NULL int_val,
    'string2' AS str_val
  FROM dual
  UNION ALL
  SELECT 1 AS typ,'doc-3' nme,10 attr,1005 int_val,NULL AS str_val FROM dual
  UNION ALL
  SELECT 1 AS typ,
    'doc-3' nme,
    15 attr,
    NULL int_val,
    'string3' AS str_val
  FROM dual
  )a
GROUP BY a.typ,
  a.nme;

------------------------------OUTPUT----------------------------------
TYP NME MAX(A.INT_VAL)  MAX(A.STR_VAL)
1   doc-3   1005    string3
2   doc-2   1004    string2
1   doc-1   1003    string1
------------------------------OUTPUT----------------------------------