SQL生成两个街道号码之间的每个街道号码并保留邮政编码

时间:2018-03-06 21:28:47

标签: sql proc-sql

我有一个数据集,其中包含街道名称和邮政编码的劣质和高级街道号码。我想生成一个数据集,其中包含每个街道号码之间的每个数字。

例如,我有这个数据集:

Inferior_Street_Number  Superior_street_number Zip_code
100                     105                    G1W2X5
100                     105                    G1W2X7
202                     204                    G1W2X7

并希望获得此输出:

Street number    Zip_code
100              G1W2X5
101              G1W2X5
102              G1W2X5
103              G1W2X5
104              G1W2X5
105              G1W2X5
100              G1W2X7
101              G1W2X7
102              G1W2X7
103              G1W2X7
104              G1W2X7
105              G1W2X7
202              G1W2X7
203              G1W2X7
204              G1W2X7

我真的很感谢你的帮助。

谢谢! 尼克(对不起我的英语)

1 个答案:

答案 0 :(得分:0)

如果您有序列号表,则此问题会分解为相当简单的连接操作。这是一个Transact-SQL示例,其中大部分都在制作序列:

-- Sample sequence table, there are tons of ways to generate these
DECLARE @Sequence TABLE(
    Number INT PRIMARY KEY
)

INSERT
    @Sequence( Number )
VALUES
    (0), ( 1 ), ( 2 ), ( 3 ), ( 4 ), ( 5 ), ( 6 ), ( 7 ), ( 8 ), ( 9 )

INSERT
    @Sequence( Number )
SELECT
    Ones.Number + 10 * Tens.Number + 100 * Hundreds.Number + 1000 * Thousands.Number
FROM
    @Sequence AS Ones
CROSS JOIN
    @Sequence AS Tens
CROSS JOIN
    @Sequence AS Hundreds
CROSS JOIN
    @Sequence AS Thousands

EXCEPT

SELECT Number FROM @Sequence


SELECT
    [Sequence].Number AS StreetNumber
,   ZipCodes.Zip_code
FROM
    @ZipCodes AS ZipCodes
JOIN    @Sequence AS [Sequence] ON (
        [Sequence].Number BETWEEN ZipCodes.Inferior_Street_Number AND ZipCodes.Superior_Street_Number
    )   
ORDER BY
    Zip_code, StreetNumber