2

我有一张这样的桌子:

PK | COL1 | COL2
----------------
1  |  A   |  a
2  |  B   |  b
3  |  C   |  c
4  |  A   |  d
5  |  A   |  e
6  |  B   |  f
7  |  C   |  g
8  |  C   |  h

我想做一个选择,我得到以下结果

COL1 | COL2
---------------
 A   | a,d,e
 B   | b,f
 C   | c,g,h

据我目前了解 SQL,如果不使用 PL/SQL“编程”一些额外的 eq,我不知道如何做到这一点,
但我寻找一个独立于 DBMS 的解决方案,就像它可以独立于 DBMS 一样好。

4

2 回答 2

2

This is an Oracle (11.2) solution:

select col1, 
       listagg(col2, ',') within group (order by col1) as col2
from the_table
group by col1;

As you need this for other DBMS as well, this would be the Postgres solution:

select col1, 
       string_agg(col2, ',' order by col1) as col2
from the_table
group by col1;

For MySQL this would be:

select col1, 
       group_concat(col2 ORDER BY col1 SEPARATOR ',') as col2
from the_table
group by col1;

For a SQL Server solution, see Vijaykumar's answer.

于 2013-11-07T08:47:17.803 回答
0

try this !!

SELECT  [col1], 
            SUBSTRING(d.col2,1, LEN(d.col2) - 1) col2
    FROM
            (
                SELECT DISTINCT [col1]
                FROM table1
            ) a
            CROSS APPLY
            (
                SELECT [col2] + ', ' 
                FROM table1 AS b 
                WHERE a.[col1] = b.[col1]
                FOR XML PATH('')
            ) d (col2) 
于 2013-11-07T08:47:04.473 回答