用于从表

时间:2018-02-09 12:54:18

标签: u-sql

数据为

    index id
        1 112
        1 112
        2 109
        2 109
        3 125
        3 125
        4 199
        4 199
        5 100
        5 100

id不是增量的,但是本质上是顺序的,将它作为GUID,这就是我为Range查询分配索引的原因

用户将给@startid @endid,我将获得此范围的行

现在我首先得到与这些id相对应的索引,如

@indexes = SELECT DISTINCT index 
 FROM @table 
WHERE id IN (@startid, endid);

结果我得到了(例如,如果@startid = 2和@endid = 4)

2
4

现在我知道范围将在2和4之间,即我希望行对应2,3和4

@result= SELECT index AS index,
         id AS id 
         FROM @data
         WHERE 
         index BETWEEN (THE TWO ENTRIES FROM @indexes)

可以使用嵌套SELECT完成此操作,但USQL不支持它。

现在有办法将@indexes视为列表并指定范围或其他内容???

1 个答案:

答案 0 :(得分:2)

U-SQL支持

BETWEEN,它只是区分大小写,例如

DECLARE CONST @startId int = 2;
DECLARE CONST @endId int = 4;


@input = SELECT *
     FROM (
        VALUES
        ( 1, 112 ),
        ( 1, 112 ),
        ( 2, 109 ),
        ( 2, 109 ),
        ( 3, 125 ),
        ( 3, 125 ),
        ( 4, 199 ),
        ( 4, 199 ),
        ( 5, 100 ),
        ( 5, 100 )
    ) AS x ( index, id );


@output =
    SELECT *
    FROM @input
    WHERE index BETWEEN @startId AND @endId;


OUTPUT @output TO "/output/output.csv"
USING Outputters.Csv(quoting:false);

我的结果:

My Results

替代方法:

    DECLARE CONST @startId int = 109;
    DECLARE CONST @endId int = 199;


    @input = SELECT *
         FROM (
            VALUES
            ( 1, 112 ),
            ( 1, 112 ),
            ( 2, 109 ),
            ( 2, 109 ),
            ( 3, 125 ),
            ( 3, 125 ),
            ( 4, 199 ),
            ( 4, 199 ),
            ( 5, 100 ),
            ( 5, 100 )
        ) AS x ( index, id );


@output =
    SELECT i. *
    FROM @input AS i
         CROSS JOIN
         (
         SELECT MIN(index) AS minIndex,
                MAX(index) AS maxIndex
         FROM @input AS i
         WHERE id IN ( @startId, @endId )
               ) AS x
    WHERE i.index BETWEEN x.minIndex AND x.maxIndex;    

    OUTPUT @output TO "/output/output.csv"
    USING Outputters.Csv(quoting:false);