| |

VerySource

 Forgot password?
 Register
Search
View: 615|Reply: 2

SQL table association problem

[Copy link]

2

Threads

7

Posts

7.00

Credits

Newbie

Rank: 1

Credits
7.00

 China

Post time: 2020-1-10 10:20:01
| Show all posts |Read mode
Table A
id name
1 aa
2 bb
3 cc

Table B
id Aid value
1 1 aaa
2 1 bbb
3 2 ccc
4 2 ddd
5 2 eee

Want to get the following records
id aa bb cc
1 aaa 0 0
2 bbb 0 0
3 0 ccc 0
4 0 ddd 0
5 0 eee 0
Can the SQL query be completed? Thank you for your advice ~
Reply

Use magic Report

0

Threads

8

Posts

5.00

Credits

Newbie

Rank: 1

Credits
5.00

 China

Post time: 2020-1-13 13:09:01
| Show all posts
create table A (id int identity (1,1), [name] char (2))
insert A select 'aa'
insert A select 'bb'
insert A select 'cc'

create table B (id int identity (1,1), Aid int, [value] char (3))
insert B select 1, 'aaa'
insert B select 1, 'bbb'
insert B select 2, 'ccc'
insert B select 2, 'ddd'
insert B select 2, 'eee'

declare @column varchar (8000)
select @ column = 'select id,'

select @ column = @ column + 'case Aid when' + convert (varchar, id) + 'then [value] else' '0' 'end [' + [name] + '],' from A
set @ column = stuff (@ column, len (@column), 1, '') + 'from B'
exec (@column)
/ *
id aa bb cc
----------- ---- ---- ----
1 aaa 0 0
2 bbb 0 0
3 0 ccc 0
4 0 ddd 0
5 0 eee 0

* /

drop table A
drop table B
Reply

Use magic Report

2

Threads

7

Posts

7.00

Credits

Newbie

Rank: 1

Credits
7.00

 China

 Author| Post time: 2020-1-13 16:18:01
| Show all posts
Thank you! !! !!
Reply

Use magic Report

You have to log in before you can reply Login | Register

Points Rules

Contact us|Archive|Mobile|CopyRight © 2008-2023|verysource.com ( 京ICP备17048824号-1 )

Quick Reply To Top Return to the list