0

我有四张桌子User,Destination,City and visited

如下

declare  @user table
 (
   UserId int identity(1,1) not null ,
   UserName nvarchar(500)
 )

 insert into @user (UserName) values ('rahul')
 insert into @user (UserName) values ('nitin')
 insert into @user (UserName) values ('yunus')

 declare @destination table 
  (
    destCode nvarchar(50),
    destName nvarchar(500)
  )

  insert into @destination select 'SWDP','ranthambore national park '
  insert into @destination select 'BTP','ghana national park '

  declare @city table 
   (
     cityId int identity(1,1) not null, 
     cityname nvarchar(500)
   )

 insert into @city select 'jaipur'
 insert into @city select 'delhi'

 -- visited table in which user id with either destCode or cityId

 declare @visited table 
   (
     UserId int , 
     LocationFrom nvarchar(500),
     LocationTo nvarchar(500),
     LocType nvarchar(50)
   )

  insert into @visited select '1','BTP','1','city'
  insert into @visited select '1','1','SWDP','dest'


  insert into @visited select '2','1','2','city'


  insert into @visited select '3','2','SWDP','dest'
  insert into @visited select '3','SWDP','BTP','dest'


 select * from @user 

 select * from @destination

 select * from @city

 select * from @visited

  select * from @visited as v
   inner join @user as u ON v.UserId=u.UserId

访问表中的位置类型列表示LocationTo类型。它的城市或位置。

现在我想加入这些表,这样我就可以获得用户从哪个城市或目的地开始并去哪个城市和目的地的数据。

预期结果如下图

这仅适用于一位用户

这仅适用于一个用户,但我需要所有用户都相同。

4

2 回答 2

2

我不确定我是否正确理解了您的表结构,但正如我所见,该表@destination既可以是起点也可以是终点?并且LocType唯一指定端点的类型(LocationToin @visited)鉴于此,我认为您必须假设 in 中的数值@Visited.LocationFrom指定了 Id in@city

那么这个查询可能有用

  SELECT u.UserName,   
    CASE WHEN ISNUMERIC(v.LocationFrom) = 1 THEN (SELECT cityName FROM @city where cityId = cast(v.LocationFrom as int)) ELSE (SELECT destName FROM @destination where destCode = v.LocationFrom) END as LocationFrom,
    CASE WHEN ISNUMERIC(v.LocationTo) = 1 THEN (SELECT cityName FROM @city where cityId = cast(v.LocationTo as int)) ELSE (SELECT destName FROM @destination where destCode = v.LocationTo) END as LocationTo
    FROM @visited AS v
   inner join @user AS u ON v.UserId=u.UserId   
于 2013-01-24T11:26:06.190 回答
2

这应该适合你:

;WITH Locations AS
   (SELECT
        CAST(CityID as nvarchar(50)) LocationId,
        CityName LocationName
    FROM
        @city
    UNION ALL
    SELECT
        DestCode,
        DestName
    FROM
        @destination)
    SELECT 
        Users.UserName,
        LocationsFrom.LocationName LocationFromName, 
        LocationsTo.LocationName LocationToName
    FROM 
        @visited Visited
        INNER JOIN Locations LocationsFrom ON LocationsFrom.LocationID = Visited.LocationFrom
        INNER JOIN Locations LocationsTo ON LocationsTo.LocationID = Visited.LocationTo
        INNER JOIN @user Users ON Visited.UserID = Users.UserID
于 2013-01-24T11:34:24.293 回答