我有一个连接查询,它给出了以下输出。
SELECT DISTINCT LOC.STATE, ORD.* FROM
(
SELECT COUNT (*) ORDERS,
ORDV.PERSON_ID PERSON_ID,
PERSON.FIRST_NAME FN,
PERSON.LAST_NAME LN,
SOURCE
FROM MY_ORD_V ORDV, EIM_PERSON PERSON
WHERE ORD_STATUS_ID NOT IN (A, C, D, F)
AND PERSON.PERSON_ID = ORDV.PERSON_ID
GROUP BY ORDV.PERSON_ID,
SOURCE,
PERSON.FIRST_NAME,
PERSON.LAST_NAME
ORDER BY 1 ASC
) ORD , MY_LOCATION_V LOC
WHERE ORD.PERSON_ID = LOC.OBJ_ID ORDER BY LOC.STATE, ORD.FN, ORD.LN
当前输出和预期输出:
答案 0 :(得分:2)
从Oracle 11g开始,您现在拥有LISTAGG analytic function。这可能是您正在寻找的(我用于测试的演示SQL):
SELECT DISTINCT state, LISTAGG(TO_CHAR(orders)||src, '|') WITHIN GROUP (ORDER BY fn, ln) OVER (PARTITION BY state, fn, ln) as orders
, fn
, ln
FROM (
SELECT 'NY' as state, 2 as orders, 'GREG' as fn, 'BOOTINE' as ln, 'DBS' as src from dual
union all
SELECT 'NY' as state, 3 as orders, 'GREG' as fn, 'BOOTINE' as ln, 'PST' as src from dual
union all
SELECT 'MA' as state, 2 as orders, 'ANN' as fn, 'SILVEST' as ln, 'DBS' as src from dual
union all
SELECT 'MA' as state, 2 as orders, 'ANN' as fn, 'SILVEST' as ln, 'PST' as src from dual
)
使用你的SQL会像:
SELECT DISTINCT state
, LISTAGG(TO_CHAR(orders)||src, '|') WITHIN GROUP (ORDER BY fn, ln) OVER (PARTITION BY state, fn, ln) as orders
, fn
, ln
FROM (
SELECT COUNT (*) ORDERS,
ORDV.PERSON_ID PERSON_ID,
PERSON.FIRST_NAME FN,
PERSON.LAST_NAME LN,
SOURCE
FROM MY_ORD_V ORDV, EIM_PERSON PERSON
WHERE ORD_STATUS_ID NOT IN (A, C, D, F)
AND PERSON.PERSON_ID = ORDV.PERSON_ID
GROUP BY ORDV.PERSON_ID,
SOURCE,
PERSON.FIRST_NAME,
PERSON.LAST_NAME
ORDER BY 1 ASC
) ORD , MY_LOCATION_V LOC
WHERE ORD.PERSON_ID = LOC.OBJ_ID
ORDER BY LOC.STATE, ORD.FN, ORD.LN
答案 1 :(得分:0)
这是一个替代版本,只是一个显示想法的伪查询。您可以在oracle中与||
连接。像这样你将始终拥有两个来源,当计数为0时。如果源需要是动态的,你仍然可以通过获取子查询中的所有不同来源(然后使用group
和{{}来实现这一点。 1}}正如@Patrick Marchand所说。)
listagg