5

查找我的表的查询时遇到问题

我有 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

4

3 回答 3

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
于 2013-10-11T07:28:45.387 回答
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 小提琴演示

于 2013-10-11T09:12:21.940 回答
1

这是 SQLFIddel 演示

以下是您可以尝试的示例查询:

select Case rownum when 1 then cast(addrid as varchar(20)) else '' end as addrid,
       Case rownum when 1 then cast(name as varchar(20)) else '' end as name,
       addr
from (select a.addrid,a.name,b.addr,dense_rank() over (partition by a.addrid order by b.addr) as rownum
  from a,b
 where a.addrid = b.addrid) T
于 2013-10-11T07:41:24.220 回答