在一列中返回多个值

时间:2013-06-07 07:12:59

标签: sql

我有两张桌子

员工

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

2 个答案:

答案 0 :(得分:5)

了解目标RDBMS肯定会很高兴。但是这个问题经常被问到,所以让我们尝试并列所有(至少是受欢迎的)并排。

对于 SQL Server

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 演示

对于 Mysql SQLite HSQLDB 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) |

答案 1 :(得分: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 FIDDLE