SELECT记录直到新值SQL

时间:2013-10-14 15:49:23

标签: sql sql-server select where

我有一张桌子

Val | Number 
08    | 1 
09    | 1 
10    | 1 
11    | 3 
12    | 0 
13    | 1 
14    | 1 
15    | 1 

我需要返回Number = 1的最后一个值(无论多少可能),直到Number更改,但不需要Number = 1的第一个实例。基本上我需要选择返回,直到Number更改为0(15 ,14,13)

在MSSQL中有没有正确的方法呢?

4 个答案:

答案 0 :(得分:2)

基于以下内容:

  

我需要返回Number = 1

的最后一个值      

基本上我需要选择返回,直到数字变为0(15,14,   13)

尝试( Fiddle demo ):

select val, number 
from T 
where val > (select max(val)
              from T
              where number<>1)

编辑以解决所有可能的组合(Fiddle demo 2

;with cte1 as
(
  select 1 id, max(val) maxOne
  from T
  where number=1 
),
cte2 as
(
  select 1 id, isnull(max(val),0) maxOther
  from T 
  where val < (select maxOne from cte1) and number<>1
)
select val, number
from T cross join 
   (select maxOne, maxOther
    from cte1 join cte2 on cte1.id = cte2.id
    ) X
where val>maxOther and val<=maxOne

答案 1 :(得分:1)

DEMO:http://sqlfiddle.com/#!3/e7d54/23

DDL

create table T(val int identity(8,1), number int)

insert into T values
(1),(1),(1),(3),(0),(1),(1),(1),(0),(2)

DML

; WITH last_1 AS (
  SELECT Max(val) As val
  FROM   t
  WHERE  number = 1
)
, last_non_1 AS (
  SELECT Coalesce(Max(val), -937) As val
  FROM   t
  WHERE  EXISTS (
           SELECT val
           FROM   last_1
           WHERE  last_1.val > t.val
         )
  AND    number <> 1
)
SELECT t.val
     , t.number
FROM   t
 CROSS
  JOIN last_1
 CROSS
  JOIN last_non_1
WHERE  t.val <= last_1.val
AND    t.val > last_non_1.val

我知道这有点冗长,但我故意用这种方式来说明方法论。

  1. 找到最高val number=1
  2. 对于val小于步骤1中找到的数字的所有值,找到val
  3. 中最大的number<>1
  4. 最后,找到属于我们在步骤1和步骤1中发现的值的行。 2。

答案 2 :(得分:1)

我认为你可以使用窗口函数,如下所示:

with cte as (
    -- generate two row_number to enumerate distinct groups
    select
        Val, Number,
        row_number() over(partition by Number order by Val) as rn1,
        row_number() over(order by Val) as rn2
    from Table1
), cte2 as (
    -- get groups with Number = 1 and last group
    select
        Val, Number,
        rn2 - rn1 as rn1, max(rn2 - rn1) over() as rn2
    from cte
    where Number = 1
)
select Val, Number
from cte2
where rn1 = rn2

<强> sql fiddle demo

答案 3 :(得分:0)

select val, count (number) from
yourtable
group by val
having count(number) > 1

having子句是此处的关键,为您提供具有多个值1的所有val。

相关问题