0

我有四张桌子

薪酬、地点、部门、工作

每一个都有 3 列 EmpId、Code、Date。

每个表中的某些记录对该表是唯一的,而某些记录存在于多个表中。

我希望将所有数据放在一个表中而没有重复,并且应该有一个新列,其中包含记录所在的表的名称

所以我们的最终数据将类似于

#Sr.no------------EmpID----------Code------Date----------Tables in which the record exists
1.--------------- E001 --------- C1 ------ 1 Feb 2014 ---------------- Pay, Department
2.--------------- E002 --------- C2 ------ 2 Jan 2014 ---------------- Location 
3.--------------- E003 --------- C3 ------ 3 Mar 2014 ---------------- Job
4.--------------- E004 --------- C4 ------ 4 Jan 2014 ---------------- Location, Pay 
5.--------------- E005 --------- C5 ------ 6 Mar 2014 ---------------- Dept, Job 
6.--------------- E006 --------- C6 ------ 3 Feb 2014 ---------------- Pay, Job, Location 
7.--------------- E007 --------- C7 ------ 2 Aug 2014 ---------------- Pay, Dept, Job, Loc 
8.--------------- E008 --------- C8 ----- 19 sep 2014 ---------------- Department 
9.--------------- E009 --------- C9 ----- 22 dec 2014 ---------------- Pay, Dept, Job, Loc
4

1 回答 1

2

用于Union all组合不同表的结果并使用附加列来区分行。

之后使用ListAgg函数到groupduplicatecomma separated values。试试这个。

SELECT EmpId,Code,Date,Listagg(Tablename,',') within GROUP (ORDER BY empid) AS Tablename 
FROM   (SELECT EmpId,Code,Date,'Pay' AS Tablename
        FROM   Pay
        UNION ALL
        SELECT EmpId,Code,Date,'Location' AS Tablename
        FROM   Location
        UNION ALL
        SELECT EmpId,Code,Date,'deparment' AS Tablename
        FROM   deparment
        UNION ALL
        SELECT EmpId,Code,Date,'job' AS Tablename
        FROM   job) A
GROUP  BY EmpId,Code,Date 

ListAgg此答案引用的功能

于 2014-12-29T19:10:57.770 回答