获取结果没有顺序ID的上一行的值

时间:2017-08-31 22:33:12

标签: sql-server sql-server-2008 tsql

我有一个TSQL表,其中的数据如下:

    ID          Value
    3252          2
    93528         3
    2351          5
    1424          19

如何创建包含给定行的先前值的附加列?我无法使用LAG()函数,因为我正在使用SQL Server 2008。

示例:

    ID          Value       PreviousValue
    3252          2             NULL
    93528         3              2
    2351          5              3
    1424          19             5

我被困在这里,因为每行的ID都是非顺序的。我相信我必须以某种方式订购行,并尝试使用以下内容:

    SELECT RANK() OVER (ORDER BY Value) as Rank, ID, Value, PreviousValue
    FROM MyTable t1
    JOIN MyTable t2 ON t1.id = t2.id
    ORDER BY Value;

结果:

    Rank        ID         Value    PreviousValue
    1       3252          2            2
    2       93528         3            3
    3       2351          5            5
    4       1424          19           9

2 个答案:

答案 0 :(得分:2)

您可以使用row_number,但是您需要加入它,因此CTE最实用。此外,如果您有重复值,rank会优于with base(id, value, rank) as ( select id, value, row_number() over (order by value) from mytable ) select t1.id, t1.value, t2.value as prev from base t1 left join base t2 on t1.rank - 1 = t2.rank order by value;

public static void svg2jpgBatik1() {
        JPEGTranscoder transcoder = new JPEGTranscoder();

        try {

            // Create a JPEG transcoder
            JPEGTranscoder t = new JPEGTranscoder();
            // Set the transcoding hints.
            t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY,
                    0.8f);

            // Create the transcoder input.
            String svgURI = new File("D:\\SVG_PATH\\map.svg").toURL().toString();
            TranscoderInput input = new TranscoderInput(svgURI);

            // Create the transcoder output.
            OutputStream ostream = new FileOutputStream("D:\\JPEG_PATH\\map.jpg");
            TranscoderOutput output = new TranscoderOutput(ostream);
            t.addTranscodingHint(JPEGTranscoder.KEY_ALTERNATE_STYLESHEET, "D:\\STYLESHEET_PATH\\style.css");
            t.addTranscodingHint(JPEGTranscoder.KEY_BACKGROUND_COLOR, Color.blue);

            // Save the image.
            t.transcode(input, output);

            // Flush and close the stream.
            ostream.flush();
            ostream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }

答案 1 :(得分:0)

我认为这就是你想要的,只需复制/粘贴即可运行样本

declare @sample table(idreal int, other varchar(100))
insert into @sample
select 13, 'a' union
select 1, 'a' union
select 18, 'b' union
select 5, 'd' union
select 4, 'ah'; 


WITH sample2 AS (
  SELECT
    rownum = ROW_NUMBER() OVER (order by idreal),
    idreal,
    other
  FROM @sample
)
SELECT s2.rownum,s2.idreal,s2prev.rownum as previousrnum,s2prev.idreal as             
previousidreal
FROM sample2 s2
LEFT JOIN sample2 s2prev on s2.rownum - 1 = s2prev.rownum