0

バスとその停車地点を表す次の表があります。

bus_table

bus stop_no station_id 
  1       1          1 
  1       2          2
  1       3          3
  2       1          7
  2       2          8
  2       3          9
  3       1          3
  3       2          4
  3       3          5
  3       4          6
  3       5          7

1駅から9駅まで行きたいです。

そのためにどのようなクエリを書くことができますか?

4

2 に答える 2

0

バス停のグラフの再帰的トラバーサル (MSSQL 2016 でテスト済み):

DECLARE @from NCHAR(4) = 'ort1';
DECLARE @to NCHAR(4) = 'ort9';

WITH [route] ([path], [lastBus], [current])
AS
    (SELECT CAST(N'' AS NVARCHAR(1000)) AS [path], CAST(N'' AS NCHAR(2)) AS [lastBus], @from AS [current]
    UNION ALL
    SELECT CAST( cur.[path] + N',' + busesAvailable.name + N' to ' + [next].stat AS NVARCHAR(1000)) AS [path],
        busesAvailable.name AS [lastBus],
        [next].stat AS [current]
    FROM [route] cur
    INNER JOIN dbo.BusStat busesAvailable ON busesAvailable.stat = cur.[current] AND busesAvailable.name <> cur.[lastBus]
    INNER JOIN dbo.BusStat [next]
        ON [next].stat <> cur.[current]
        AND [next].name = busesAvailable.name)
SELECT TOP 1 [route].[path]
FROM [route]
WHERE [route].[current] = @to;

テーブルを考慮すると、次のように作成されます。

CREATE TABLE [dbo].[BusStat]
(
    [name] NCHAR (2) NOT NULL,
    [stat] NCHAR (4) NOT NULL
);
INSERT INTO [dbo].[BusStat] ([name], [stat])
SELECT 'b1',    'ort1' UNION ALL
SELECT 'b1',    'ort2' UNION ALL
SELECT 'b1',    'ort3' UNION ALL
SELECT 'b2',    'ort7' UNION ALL
SELECT 'b2',    'ort8' UNION ALL
SELECT 'b2',    'ort9' UNION ALL
SELECT 'b3',    'ort3' UNION ALL
SELECT 'b3',    'ort4' UNION ALL
SELECT 'b3',    'ort5' UNION ALL
SELECT 'b3',    'ort6' UNION ALL
SELECT 'b3',    'ort7';
于 2016-07-03T14:37:36.760 に答える