2017-04-05 72 views
-1

我在SQL服务器2个表如下 -连接表给冗余数据

emp_detail

EID ENAME  BHDT  SEXC GRPT MSTA CITY 
2  Ana  5/10/1955 M  43000 M  Mexico 
5  Christina 4/20/1976 F  34000 S  Luea 
1  Maria  3/21/1952 F  55000 S  Berlin 
3  Antonio 10/15/1986 M  45630 U  Mexico 
7  RSTUV  1/14/1945 M  12672 S  New york 
6  Kristy 2/1/1967 F  23000 U  Texas 
4  Thomas 3/5/1962 M  43280 S  London 

job_detail

EID Job_Type_Code Job Val Code EFDT 
1 Plan   ESI    3/7/1950 
1 LOC    20    4/20/1970 
1 Plan   ESAL   3/9/1966 
2 Plan   GARLND   12/15/1956 
2 Union   15    11/6/1961 
3 Plan   ESI    11/6/1986 
3 LOC    15    11/6/1967 
3 LOC    15    11/6/1986 

我想要的结果是 -

EID ENAME BHDT  SEXC GRPT MSTA CITY plan_det loc_det Union_det Max_date 
1 Maria 3/21/1952 F 55000 S Berlin ESAL  20  (null) 4/20/1970 
2 Ana  5/10/1955 M 43000 M Mexico GARLND (null) 15  12/15/1956 
3 Antonio 10/15/1986 M 45630 U Mexico ESI  15  (null) 11/6/1986 

我已经试过以下查询但没有成功 -

SELECT e.eid, e.ename, e.bhdt, e.sexc, e.grpt, e.msta, e.city, 
    case when j.JT_code = 'Plan' then JV_code end as plan_detail, 
    case when j.JT_code = 'LOC' then JV_code end as loc_detail, 
    case when j.JT_code = 'Union' then JV_code end as Union_detail, 
    max(EFDT) latest_date 
FROM emp_detail e inner join job_detail j 
on e.eid = j.eid 
group by e.eid, e.ename, e.bhdt, e.sexc, e.grpt, e.msta, e.city, JT_code, JV_code 

任何帮助,非常感谢。

回答

1

您有EAV记录。您需要总结这些值。使用您的查询作为基地,group by是一种方便的方法:

SELECT e.eid, e.ename, e.bhdt, e.sexc, e.grpt, e.msta, e.city, 
     max(case when j.JT_code = 'Plan' then JV_code end) as plan_detail, 
     max(case when j.JT_code = 'LOC' then JV_code end) as loc_detail, 
     max(case when j.JT_code = 'Union' then JV_code end) as Union_detail, 
     max(EFDT) as latest_date 
FROM emp_detail e inner join 
    job_detail j 
    on e.eid = j.eid 
GROUP BY e.eid, e.ename, e.bhdt, e.sexc, e.grpt, e.msta, e.city; 
+0

这是我唯一的原因,你是死难的风扇上SO。我希望如果能和你说话.... –