我有相当复杂的遗留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中的任何内容,因此我想将exising输出转换为如下所示:
type | name | attr-A | attr-B
----------------------------------
1 | doc-1 | 1003 | string1
2 | doc-2 | 1004 | string2
1 | doc-3 | 1005 | string3请帮助我按照我提议的方式编写处理现有输出的查询。
发布于 2015-12-07 06:54:47
尝尝这个。它将帮助你解决你的问题。有任何问题请告诉我。
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----------------------------------https://stackoverflow.com/questions/34127850
复制相似问题