优化的SQL查询,用于从Microsoft SQL Server DB检索特定的记录集

时间:2016-08-11 11:29:52

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

我想从表格中的列中检索数据集。 我的情景是: 我有一个名为table1_data的表,在该表中有一个名为“clm_Name”的列,列中的数据是这样的

a
b
c
a
b
c
a
b
a
b
c
a
a
b
c

我想在abc处于有序状态时检索数据,如果订单更改它不应该检索。(即,如果我们在给定数据上写一个查询,输出应该是 abcabc ab abc a abc )只有粗体字母应显示在输出中。

1 个答案:

答案 0 :(得分:1)

如果您有要排序的列,则可以执行以下操作:

DECLARE @Tbl TABLE (OrderId INT, val NVARCHAR(1))

INSERT INTO @Tbl        
VALUES  
(1,'a'),
(2,'b'),
(3,'c'),
(4,'a'),
(5,'b'),
(6,'c'),
(7,'a'),
(8,'b'),
(9,'a'),
(10,'b'),
(11,'c'),
(12,'a'),
(13,'a'),
(14,'b'),
(15,'c')


;WITH  CTE
AS
(   
    SELECT 
        *, 
        ROW_NUMBER() OVER (ORDER BY (SELECT OrderId)) RowId
    FROM @Tbl
), Result
AS 
(
    SELECT  
        CurrRow.RowId
    FROM
        CTE CurrRow LEFT JOIN 
        (SELECT CTE.val , CTE.RowId - 1 RowId FROM CTE) NextRow ON CurrRow.RowId = NextRow.RowId LEFT JOIN 
        (SELECT CTE.val , CTE.RowId + 1 RowId FROM CTE) PrivRow ON CurrRow.RowId = PrivRow.RowId
    WHERE
        PrivRow.val = 'a' AND 
        CurrRow.val = 'b' AND 
        NextRow.val = 'c'
)


SELECT 
    * 
FROM 
    CTE C
WHERE
    C.RowId IN ( 
                    SELECT Result.RowId FROM Result
                    UNION ALL
                    SELECT Result.RowId - 1 FROM Result
                    UNION ALL
                    SELECT Result.RowId + 1 FROM Result
                )
ORDER BY C.OrderId

输出:

OrderId val RowId
1       a   1
2       b   2
3       c   3
4       a   4
5       b   5
6       c   6
9       a   9
10      b   10
11      c   11
13      a   13
14      b   14
15      c   15