T-SQL选择具有超过阈值的3个连续int列的行

时间:2014-06-18 09:44:27

标签: sql-server tsql

我有一张表,记录每个月的分数。我想运行一个查询来获得连续3个月得分超过100的行。

我已经看过以下example,它适用于超过阈值的连续行。但是我正在努力使其适应列而不是行。我想我应该使用'OVER(PARTITION BY)',但我不确定如何。

我已经开始sqlfiddle我希望有人可以帮助我。

谢谢。

2 个答案:

答案 0 :(得分:2)

不幸的是,当您将数据存储在这样的列中时,查询并不像使用更规范化的格式那样容易。

在你的情况下,蛮力方法并不是那么糟糕:

select *
from t
where (jan > 100 and feb > 100 and mar > 100) or
      (feb > 100 and mar > 100 and apr > 100) or
      (mar > 100 and apr > 100 and may > 100) or
      (apr > 100 and may > 100 and jun > 100) or
      (may > 100 and jun > 100 and jul > 100) or
      (jun > 100 and jul > 100 and aug > 100) or
      (jul > 100 and aug > 100 and sep > 100) or
      (aug > 100 and sep > 100 and oct > 100) or
      (sep > 100 and oct > 100 and nov > 100) or
      (oct > 100 and nov > 100 and decm > 100)

答案 1 :(得分:1)

;with cte as
(
    SELECT 
        name, 
        case m 
            when 'jan' then 1
            when 'feb' then 2
            when 'mar' then 3
            when 'apr' then 4
            when 'may' then 5
            when 'jun' then 6
            when 'jul' then 7
            when 'aug' then 8
            when 'sep' then 9
            when 'oct' then 10
            when 'nov' then 11
            when 'decm' then 12 end as MonthNum,
        m, 
        score
    FROM 
       (SELECT name, jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, decm
       FROM t) p
    UNPIVOT
       (score FOR m IN 
          (jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, decm)
    )AS unpvt
)  
select 
  c.name, 
  c.m as 'Start month', 
  c.score as 'Score for start month',
  c_plus_1.score as 'Score for start month + 1',
  c_plus_2.score as 'Score for start month + 2'
from cte c 
    inner join cte c_plus_1 on c.name = c_plus_1.name and c.MonthNum + 1 = c_plus_1.MonthNum 
    inner join cte c_plus_2 on c.name = c_plus_2.name and c.MonthNum + 2 = c_plus_2.MonthNum 
where c.score > 100 and c_plus_1.score > 100 and c_plus_2.score > 100