我正在查询多个表,需要组合一个名为" NOTES"的表中的所有值。对于给定的ID。
这就是我所拥有的:
SELECT e.HR_NUMBER, s.SALES_ID, s.SALES_ID_TYPE, m.REGION_ID,
e.ADDED_DATE_TIME, e.TERMINATION_DATE, s.HOUSE_ACCOUNT,
(SELECT t.NOTE FROM employee_note t WHERE e.hr_number = t.HR_NUMBER)
FROM employee e
INNER JOIN sales_id s
ON e.HR_NUMBER = s.HR_NUMBER
LEFT JOIN market m
ON s.MARKET_ID = m.MARKET_ID
LEFT JOIN region r
ON m.REGION_ID = r.REGION_ID
LEFT JOIN sales_id_type t
ON s.SALES_ID_TYPE = t.SALES_ID_TYPE
LEFT JOIN employee_note n
ON e.HR_NUMBER = n.HR_NUMBER
问题显然是当给定ID有多个音符时它不起作用。
如果我执行以下sql:
SELECT e.HR_NUMBER, s.SALES_ID, s.SALES_ID_TYPE, m.REGION_ID,
e.ADDED_DATE_TIME, e.TERMINATION_DATE, s.HOUSE_ACCOUNT, n.NOTE
FROM employee e
INNER JOIN sales_id s
ON e.HR_NUMBER = s.HR_NUMBER
LEFT JOIN market m
ON s.MARKET_ID = m.MARKET_ID
LEFT JOIN region r
ON m.REGION_ID = r.REGION_ID
LEFT JOIN sales_id_type t
ON s.SALES_ID_TYPE = t.SALES_ID_TYPE
LEFT JOIN employee_note n
ON e.HR_NUMBER = n.HR_NUMBER
我得到以下内容:
000000 E0019 XXX XXX 23-JUN-10 N NOTE 1
000000 E0019 XXX XXX 23-JUN-10 N NOTE 2
000000 E0019 XXX XXX 23-JUN-10 N NOTE 3
我真正需要的是:
000000 E0019 XXX XXX 23-JUN-10 N NOTE 1, NOTE 2, NOTE 3
我知道你可以在我的版本中使用LISTAGG来支持它。此外,我在stackoverflow上尝试了其他几个答案,但我似乎无法让它们为我的查询工作。
非常感谢任何帮助。
答案 0 :(得分:1)
使用Common Table Expression [cte]检查以下查询是否有帮助:
WITH CTE AS
(
SELECT e.HR_NUMBER, s.SALES_ID, s.SALES_ID_TYPE, m.REGION_ID,
e.ADDED_DATE_TIME, e.TERMINATION_DATE, s.HOUSE_ACCOUNT, n.NOTE,
, ROW_NUMBER () OVER (ORDER BY NOTE ) rn,
COUNT (*) OVER () cnt
FROM employee e
INNER JOIN sales_id s
ON e.HR_NUMBER = s.HR_NUMBER
LEFT JOIN market m
ON s.MARKET_ID = m.MARKET_ID
LEFT JOIN region r
ON m.REGION_ID = r.REGION_ID
LEFT JOIN sales_id_type t
ON s.SALES_ID_TYPE = t.SALES_ID_TYPE
LEFT JOIN employee_note n
ON e.HR_NUMBER = n.HR_NUMBER
)
SELECT HR_NUMBER, SALES_ID, SALES_ID_TYPE,REGION_ID,
ADDED_DATE_TIME, TERMINATION_DATE, HOUSE_ACCOUNT,
SUBSTR (SYS_CONNECT_BY_PATH (NOTE , ','), 2) csv
FROM CTE
WHERE rn = cnt
START WITH rn = 1
CONNECT BY rn = PRIOR rn + 1;
我基本上尝试将您的查询与提供here
的示例解决方案合并