在查找我的表格时遇到问题
我有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 |
我到目前为止已经尝试过查询
答案 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
,结果与您想要的相同。