查询将多个相同记录分组为1行

时间:2013-10-11 07:21:31

标签: sql postgresql

在查找我的表格时遇到问题

我有2张表A和表B如下

table A 
---------------------
|   Name   | addrid |
---------------------
|   zlai   |   1    |
|   blai   |   2    |

table B 
---------------------
| addrid |   addr     |
---------------------
|   1    |   AMERICA  |
|   1    |   SPAIN    |
|   1    |   MEXICO   |
|   2    |   TURKEY   |

我需要的结果是

--------------------------
|   Num  | Name  | addr    |
--------------------------
|    1   | zlai  | AMERICA |               
|        |       | SPAIN   |
|        |       | MEXICO  |
|    2   | blai  | TURKEY  |

我到目前为止已经尝试过查询

http://sqlfiddle.com/#!12/3ac39/12

2 个答案:

答案 0 :(得分:5)

SELECT  CASE WHEN No != 1
             THEN ''
             ELSE CAST(a.addrid AS VARCHAR(20))
        END  AS Num,
        CASE WHEN No != 1
             THEN ''
             ELSE name
        END  AS name,
        addr
FROM
        (
          SELECT  ROW_NUMBER() OVER (PARTITION BY a.addrid 
                                     ORDER BY name DESC) AS No,
                  name, 
                  addr,
                  a.addrid
          FROM    a LEFT JOIN b ON a.addrid = b.addrid
        ) a
ORDER   BY a.addrid

答案 1 :(得分:2)

我尝试将addrid值修改为101和325(例如)

table A 
---------------------
|   Name   | addrid |
---------------------
|   zlai   |   101  |
|   blai   |   325  |

table B 
---------------------
| addrid |   addr     |
---------------------
|   101  |   AMERICA  |
|   101  |   SPAIN    |
|   101  |   MEXICO   |
|   325  |   TURKEY   |

查询是:

SELECT  CASE WHEN No != 1
             THEN ''
             ELSE CAST(row AS VARCHAR(20))
        END  AS Num,
        CASE WHEN No != 1
             THEN ''
             ELSE name
        END  AS name,
        addr
FROM
        (
          SELECT  ROW_NUMBER() OVER (PARTITION BY a.addrid 
                                     ORDER BY name DESC) AS No,
                  name, 
                  addr,
                  DENSE_RANK() OVER (ORDER BY a.addrid) "row"
          FROM    a LEFT JOIN b ON a.addrid = b.addrid
        ) a
ORDER   BY row

,结果与您想要的相同。

SQL Fiddle Demo