这是我的2个规范化表格,其中包含Clientid到电话表
(ClientID int Primary key,
FName varchar(25),
LName varchar(25),
HomeAddress varchar(50))
CREATE TABLE Telephone
(TelephoneID tinyint IDENTITY(1,1)Primary key,
TelephoneNo int,
ClientID int foreign key references Client(ClientID))
所以我的Client表的值..
ClientID | FName | LName | HomeAddress
1 marvin Biu p.guevarra st.
2 harry sendon cali st.
进入我的电话表..
TelephoneID | TelephoneNo | ClientID
1 1234567 1
2 7654321 1
3 2222222 2
因为客户端可能有多个电话号码 所以我想成为这样的..
ClientID | FName | LName | HomeAddress | Telephones
1 marvin Biu p.guevarra st. 1234567, 7654321
2 harry sendon cali st. 2222222
我只提出像这样的代码
select distinct lname, CAST(telephoneno AS VARCHAR(10)) + ',' + CAST(telephoneno AS VARCHAR(10)) as Telephones
from telephone
left join client
on client.clientid = telephone.clientid
这样结束了..
LName | Telephones
Biu 1234567, 1234567
Biu 7654321, 7654321
sendon 2222222
请有人帮忙,表格最终会以如上所示的简单形式结束, 我真的希望1234567 telephoneno加入7654321 telephoneno,在电话列之间使用一个Lname“Biu”列进行昏迷。多数民众赞成1排。 :/
答案 0 :(得分:1)
SELECT
lname,
Telephones = STUFF((SELECT ','+ CAST(t.telephoneno AS VARCHAR(10))
FROM telephone t
WHERE t.clientid = c.clientid
For XML PATH('')
),1,1,'')
FROM client c
答案 1 :(得分:0)
始终在联接中限定您的表格,这样可以更清楚地了解正在发生的事情:
select distinct t.lname, CAST(t.telephoneno AS VARCHAR(10)) + ',' + CAST(c.telephoneno AS VARCHAR(10)) as Telephones
from telephone t
left join client c
on c.clientid = t.clientid