将两个SQL查询合并为一行

时间:2017-07-31 16:46:40

标签: sql

我的数据库中有两个表:

表1

|   id   |   name     |
+--------+------------+
|  100   |   john     |
|  200   |   Ali      |

表2

|  id  |  account  |  bank  |
+------+-----------+--------+
| 100  |  AAAAAAA  |  bnk1  |
| 100  |  BBBBBBB  |  bnk2  |
| 200  |  XXXXXXX  |  bnk1  |

这意味着" john"在两个不同的银行有两个不同的账户

现在我想要一个查询来显示:

|  id  |            tab2            |
+------+----------------------------+
| 100  | AAAAAAAbank1 - BBBBBBBbnk2 |
| 200  |        XXXXXXXbnk1         |

有可能吗?

1 个答案:

答案 0 :(得分:0)

假设您正在使用MS SQL Server

SELECT  DISTINCT
        Table1.id,
        LEFT(STUFF((SELECT account + bank + '-' FROM Table2 WHERE id = Table1.id FOR XML PATH ('')), 1, 1, ''),LEN(STUFF((SELECT account + bank + '-' FROM Table2 WHERE id = Table1.id FOR XML PATH ('')), 1, 1, ''))-1)
FROM    Table1
        JOIN Table2
            ON Table1.id = Table2.id