2

在 POSTGRESql::

我有一个带列的TableA

id  |   descr     |  team      |  status
254 | NSWemp      | Sales      | A
365 | NSW,VIC emp | Sales      | L
345 | NSW emp     | Post Sales | A

我有一个带列的TableB

id   | state
254  | NSW
365  | NSW
365  | VIC
365  | QLD
2345 | NT
2345 | NSW

我的要求::有没有办法获得输出为::

id     |    descr    |  team       |   status  |    state
254    | NSWemp      | Sales       | A         | NSW
365    | NSW,VIC emp | Sales       | L         | NSW,VIC,QLD
2345   | NSW emp     | Post Sales  | A         | NT,NSW

我曾尝试使用 JOINS 和 GROUP BY,但我无法让它工作!有什么建议让它工作吗?

SELECT TABLEA.ID,DESCR,TEAM,STATUS,STATE 
     FROM TABLEA 
     inner join TABLEB   ON TABLEA.ID = TABLEB.ID 
   GROUP BY  TABLEA.ID,DESCR,TEAM,STATUS,TABLEB.STATE;

      id  |    descr    |    team    | status | state
    ------+-------------+------------+--------+-------
     2345 | NSW emp     | Post Sales | A      | NT
      365 | NSW,VIC emp | Sales      | L      | NSW
      254 | NSWemp      | Sales      | A      | NSW
     2345 | NSW emp     | Post Sales | A      | NSW
      365 | NSW,VIC emp | Sales      | L      | QLD
      365 | NSW,VIC emp | Sales      | L      | VIC

(6 rows)
4

1 回答 1

0

你应该使用ARRAY_AGG()

SELECT TABLEA.ID,
       DESCR,
       TEAM,
       STATUS,
       array_agg(STATE) 
       FROM TABLEA 
        inner join TABLEB
          ON TABLEA.ID = TABLEB.ID 
       GROUP BY TABLEA.ID,DESCR,TEAM,STATUS

SQL Fiddle 演示

于 2013-07-05T10:57:52.693 回答