【问题标题】:how to combine data from two table?如何合并两个表中的数据?
【发布时间】:2015-10-06 16:58:29
【问题描述】:

看到我有两个类似的表

表 1:剧院详情

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:城市详细信息

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

我想要这样的输出 可以吗?我是 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

【问题讨论】:

  • 当然可以,不过这种布局最好在表现层处理。
  • 表示层是什么意思?我正在使用简单的 asp.net gridview 控件来显示相同​​的输出..
  • 最好在 asp.net 中使用中继器,并且当您遍历数据行时,如果城市发生变化,请添加仅包含城市名称的行,然后再添加一行列标题,然后继续添加数据行,直到再次更改城市。
  • 是的,你是对的,我们可以使用中继器控件而不是 gridview。但为此我还需要创建数据集,所以如果你能帮我创建查询,我会很高兴
  • @Sanjay 你为什么不试试你发布的查询作为转发器的查询?

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


【解决方案1】:

这将是您想要的查询

    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

【讨论】:

    猜你喜欢
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多