2

私は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 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 、SQLiteHSQLDB 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 に答える