我的数据库中有以下表格
表用户
user_id phone
1 2222222222
1 3333333333
2 1111111111
2 4444444444
2 5555555555
3 6666666666
3 7777777777
表users_phone
user_id full_name phone1 phone2 phone3
1 user1 2222222222 3333333333
2 user2 1111111111 4444444444 5555555555
3 user3 6666666666 7777777777
创建一个为每个用户添加电话列的SQL语句, 我希望我的SELECT语句返回以下内容:
select * from
(select phone1 from users_phone as P
,(select phone2 from users_phone)as P
(select phone3 from users_phone)as P)from users as U
where U.user_id=P.user_id
我试图创建一个执行以下操作的SQL语句,但显然失败了。
就我已经试图解决这个问题而言,这里已经有了。
close.onclick = function(){
checker('id'); // <-- are you sure you want to pass static string here?
};
我一直在融化我的大脑,试图弄清楚如何在查询中做甚至可以做任何帮助都会非常感激!
答案 0 :(得分:0)
在SQl Server中,我会使用with和row_number来执行此操作: 像那样:
;with cte as (
select u.userId,
p.phone, row_number() over (partition by u.userId order by u.userId) as rn
from @tb1 u
join @tb2 p on u.userId = p.userId )
select u.Userid, u.name,
(select cte.phone from cte where cte.userId = u.UserId and cte.rn = 1) as phone1,
(select cte.phone from cte where cte.userId = u.UserId and cte.rn = 2) as phone2,
(select cte.phone from cte where cte.userId = u.UserId and cte.rn = 3) as phone3
from @tb1 u