如何组合两个表的数据?

时间:2015-10-06 16:58:30

标签: c# sql-server vb.net sql-server-2008 sql-server-2012

请参阅我有两个表,如

表1:TheaterDetail

t_id    t_Address    t_Name   c_id
1       ahmedabad    Cinemax1   1
2       Baroda       Cinemax2   2
3       Jamnagar     Cinemax3   3
4       Rajkot       Cinemax4   4
5       Surat        Cinemax5   5
6       Junagadh     Cinemax2   2

表2:CityDetails

c_id    City_name
1       Ahm
2       Bar
3       Jam
4       Raj
5       Sur

我想要Out To Like那有可能吗?我是sql的新手,所以我发现它很难。 我希望列名显示在输出(t_address,t_name)

Ahm 
t_address   t_name
ahmedabad   Cinemax1
Bar 
t_address   t_name
Baorda  Cinemax2
Junagadh Cinemax2
Jam 
t_address   t_name
Jamnagar    Cinemax3
Raj 
t_address   t_name
Rajkot  Cinemax4
Sur 
t_address   t_name
Surat   Cinemax5

我做了两个像这样的查询

 select distinct city_name from CityDetail A inner join TheaterDetail B

    on A.c_id = B.c_id where a.c_id= 2

   city_name
   Bar

和其他查询一样

select t_Address,t_Name from TheaterDetail C inner JOin CityDetail D
on C.c_id = D.c_id where D.c_id= 2

t_Address   t_Name
Baroda      Cinemax2
Junagadh    Cinemax2

如果我把条件放在city_id = 2

上,我的愿望就是这样
Bar 
t_address   t_name
Baorda      Cinemax2
Junagadh    Cinemax2

1 个答案:

答案 0 :(得分:0)

这将是您想要的查询

    drop table Tbl1
    Create table Tbl1
    (
        iSrno int identity(1,1) not null,
        c_id numeric(18,2),
        city_name nvarchar(500) 
        ,t_name nvarchar(500)
    )

    Insert into Tbl1 
    select c_id,city_name as city_name, '' as t_name from CityDetails
    Union
    select c_id, 't_address','t_name'  from CityDetails

    Insert into Tbl1 
    select b.c_id,a.t_address,a.t_name  from TheaterDetail as a 
    Inner join CityDetails b on a.c_id= b.c_id

select * from Tbl1 Order by c_id asc , iSrno asc