2

我有两张桌子

员工

Empid Ename Eage Eadd Ephone
1      x     23   b    677
2      y     24   h    809 
3      z     34   u    799

部门

Did  fkEmpid dname ddescription
123    1     test   test
234    1     test1  test1
667    2     hello  hello

最后我想要这样的东西

Ename Eage  Eadd Ephone  dname
x      23     b   677     test,test1
y      24     h   809     hello
z      34     u   799     null

请帮我处理 SQL

4

2 回答 2

5

知道目标 RDBMS 肯定会很好。但是这个问题经常被问到,所以让我们试着并排列出所有(至少是流行的)。

对于SQL 服务器

SELECT e.Ename, e.Eage, e.Eadd, e.Ephone, d.dname
  FROM Employee e LEFT JOIN 
(
  SELECT fkEmpid,
         STUFF((SELECT ',' + dname 
                    FROM Department 
                   WHERE fkEmpid = t.fkEmpid 
                     FOR XML PATH('')) , 1 , 1 , '' ) dname
    FROM Department t
   GROUP BY fkEmpid
) d
    ON e.Empid = d.fkEmpid

这是SQLFiddle演示

对于MysqlSQLiteHSQLDB 2.X

SELECT e.Ename, e.Eage, e.Eadd, e.Ephone, d.dname
  FROM Employee e LEFT JOIN 
(
  SELECT fkEmpid,
         GROUP_CONCAT(dname) dname
    FROM Department t
   GROUP BY fkEmpid
) d
    ON e.Empid = d.fkEmpid

这是SQLFiddle演示 (MySql)
这是SQLFiddle演示 (SQLite)

对于Oracle 11g

SELECT e.Ename, e.Eage, e.Eadd, e.Ephone, d.dname
  FROM Employee e LEFT JOIN 
(
  SELECT fkEmpid,
         LISTAGG (dname, ',') WITHIN GROUP (ORDER BY dname) dname
    FROM Department t
   GROUP BY fkEmpid
) d
    ON e.Empid = d.fkEmpid

这是SQLFiddle演示

对于PostgreSQL 9.X

SELECT e.Ename, e.Eage, e.Eadd, e.Ephone, d.dname
  FROM Employee e LEFT JOIN 
(
  SELECT fkEmpid,
         string_agg(dname, ',') dname
    FROM Department t
   GROUP BY fkEmpid
) d
    ON e.Empid = d.fkEmpid

这是SQLFiddle演示

所有情况下的输出:

| ENAME | EAGE | EADD | EPHONE |      DNAME |
---------------------------------------------
|     x |   23 |    b |    677 | test,test1 |
|     y |   24 |    h |    809 |      hello |
|     z |   34 |    u |    799 |     (null) |
于 2013-06-07T07:31:07.017 回答
0

RDBMS视为SQL SERVER 2008

select E.Ename,E.Eage,E.Eadd,E.Ephone,D.dname
into Table1
from Employee E
left join Deparment D on E.Empid=D.fkEmpid

select t1.[Ename], t1.[Eage], t1.[Eadd], t1.[Ephone],
STUFF((
    SELECT ', ' + t2.dname
    FROM Table1 t2
    WHERE t2.Ename = t1.Ename
      AND t2.Eage=t1.Eage
      AND t2.Eadd=t1.Eadd
      AND t2.Ephone=t1.Ephone
    FOR XML PATH (''))
  ,1,2,'') AS Names
FROM Table1 t1
GROUP BY t1.Ename,t1.[Eage], t1.[Eadd], t1.[Ephone];

SQL 小提琴

于 2013-06-07T07:30:57.670 回答