源和目标纬度/经度的可能排列

时间:2018-08-23 17:29:06

标签: sql-server

我在SQL Server中有一个名为#Places1的下表 enter image description here

A-> B

C-> D

E-> F 我正在尝试获取此表的所有可能排列,但是Origin必须在Destination之前输入IN。

问题是我正在生成一些没有起点的目的地。您能指导/帮助我找到解决方案吗?

create table #places1
(

idgeneric int identity(1,1)

, id AS cast(CONCAT('0',cast(idgeneric as varchar(10))) as nvarchar(max))

, CatCode as cast(char(64+idgeneric) as nvarchar(max))

,OB_FREIGHT_ORDER_ID bigint

, lat decimal(9,6)

, long decimal(9,6)

, source nvarchar(max))

insert into #places1(OB_FREIGHT_ORDER_ID, lat, long, source)

select 25, 40.066863, -76.776681, 'Origin'

union all
select 25, 41.671810, -72.834214, 'Destination'

union all
select 26, 40.140015,-74.191128, 'Origin'

union all
select 26,41.738134, -72.198242, 'Destination'

union all
select 35, 41.488488,-74.234148, 'Origin'

union all
select 35,40.818434, -73.883721, 'Destination'

select * from #places1

下面是我到目前为止的代码

Declare @counter int
Select  @counter = COUNT(*)
from    #places1;

DECLARE @Terminus TABLE (OD INT, node nvarchar(max))

INSERT INTO @Terminus

SELECT 1, id 
FROM (
      SELECT id FROM #places1 
      where source = 'origin'      

  EXCEPT 

      SELECT id 
      FROM #places1
      where source = 'Destination') x
UNION ALL
SELECT 2, id 
FROM (
        SELECT id
        FROM #places1 
        where source = 'Destination'
EXCEPT 
        SELECT id 
        FROM #places1
        where source = 'origin') x


;With Permutations (permutation, IDs, source, Depth, count_origin,     count_destination)
as
(
Select c.CatCode
,c.ID + ';'
, cast(source as nvarchar(max))
--,lat
--,long
--,lat
--,long
--,parent
,Depth = 1
,case when source = 'Origin' then 1 else 0 end 
,case when source = 'Destination' then 1 else 0 end 
From #places1 c
WHERE id IN (SELECT node FROM @Terminus WHERE OD = 1)

union all

SELECT permutation + c.CatCode
,IDs + c.ID + ';' as IDs
,cast(p.source + '->'+ c.source as nvarchar(max)) as source
--,c.lat
--,c.long
--,p.d_lat
--,p.d_long
--,p.parent
,Depth = Depth + 1
,count_origin + case when c.source = 'Origin' then 1 else 0 end 
,count_destination + case when c.source = 'Destination' then 1 else 0 end 
FROM Permutations p
INNER JOIN #places1 c 
ON IDs not like '%' + ID + ';%'         
where (count_destination + case when c.source = 'Destination'      then     1 else 0 end <= count_origin + case when c.source = 'Origin' then 1 else 0 end ))

Select distinct *
from Permutations
where depth = @counter

请参见结果问题。.06不能在没有其起源05的情况下生成

see result issue..06 shouldn't be generated without its origin 05

0 个答案:

没有答案