选择元素将在未来2个月内显示。 SQL SERVER

时间:2015-05-28 03:13:38

标签: sql-server

这是我的SELECT查询的结果。

Code    Name         MONTH
------- ------------ -----------
Cust3   CustName3    1
Cust2   CustName2    2
Cust5   CustName5    3
Cust2   CustName2    5
Cust2   CustName2    6
Cust3   CustName3    7
Cust6   CustName6    8
Cust1   CustName1    10
Cust1   CustName1    11
Cust3   CustName3    12

现在我想连续两个月选择具有相同Code值的行,例如{5}在第5和第6个月是连续的,Cust2在第10个月是连续的11:

Cust1

3 个答案:

答案 0 :(得分:3)

我假设基础表是非规范化的并且具有此模式:

Code varchar(n),
Name nvarchar(n),
Month int

......并且每个月只有一行。

我们可以使用the LAG function in T-SQL来比较邻居行。我们不需要可选的OVER partition-by子句,因为它是单个数据集组:

SELECT
    [Code],
    [Month]
FROM
(
    SELECT
        [Code],
        LAG( [Code], 1 ) AS LastCode
        [Month],
        LAG( [Month], 1 ) AS LastMonth
   FROM
       [sourceTable]
   ORDER BY
       [Month] ASC
) AS Lagged
WHERE
    Lagged.[Code] = Lagged.LastCode
    AND 
    Lagged.[Month] = Lagged.LastMonth

答案 1 :(得分:3)

以下是使用ROW_NUMBERCOUNT() OVER的另一种方法:

SQL Fiddle

WITH Cte AS(
    SELECT *,
        RN = [Month] - ROW_NUMBER() OVER(PARTITION BY Code ORDER BY [Month])
    FROM TestData
),
Cte2 AS(
    SELECT *,
        CC = COUNT(*) OVER(PARTITION BY Code, RN)
    FROM Cte
)
SELECT
    Code, Name, [Month]
FROM Cte2
WHERE CC >= 2

答案 2 :(得分:0)

以上两个答案非常简洁。这是解决这个问题的另一种替代方法(example),也许并不优雅:

select * from
(
  -- join to itself, but for month - join to previous month
  select a.code, a.month
  from test a
  inner join test b on a.code=b.code and a.month = b.month-1

  union all

  -- join to itself, but for month - join to next month
  select a.code, a.month
  from test a
  inner join test b on a.code=b.code and a.month = b.month+1
) a
order by a.code, a.month