有条件获取数据

时间:2019-02-18 12:23:03

标签: sql database sql-server-2008

declare @t table (
    Id      int ,
    Section int,
    Moment  date
);

insert into @t values
(   1   ,   1   , '2014-01-01'),
(   2   ,   1   , '2014-01-02'),
(   3   ,   1   , '2014-01-03'),
(   4   ,   1   , '2014-01-04'),
(   5   ,   1   , '2014-01-05'),

(   6   ,   2   , '2014-02-06'),
(   7   ,   2   , '2014-02-07'),
(   8   ,   2   , '2014-02-08'),
(   9   ,   2   , '2014-02-09'),
(   10  ,   2   , '2014-02-10'),

(   11  ,   3   , '2014-03-11'),
(   12  ,   3   , '2014-03-12'),
(   13  ,   3   , '2014-03-13'),
(   14  ,   3   , '2014-03-14'),
(   15  ,   3   , '2014-03-15');

获取这样的数据

select * from @t

Id  Section Moment
1   1   2014-01-01
2   1   2014-01-02
3   1   2014-01-03
4   1   2014-01-04
5   1   2014-01-05
6   2   2014-02-06
7   2   2014-02-07
8   2   2014-02-08
9   2   2014-02-09
10  2   2014-02-10
11  3   2014-03-11
12  3   2014-03-12
13  3   2014-03-13
14  3   2014-03-14
15  3   2014-03-15

但是我想要像this.group by 3和Section明智的数据

如果ant节有5行,则会创建2个组。

Id  Section Moment  Group by 3
1   1   1/1/2014    1
2   1   1/2/2014    1
3   1   1/3/2014    1
4   1   1/4/2014    2
5   1   1/5/2014    2
6   2   2/6/2014    3
7   2   2/7/2014    3
8   2   2/8/2014    3
9   2   2/9/2014    4
10  2   2/10/2014   4
11  3   3/11/2014   5
12  3   3/12/2014   5
13  3   3/13/2014   5
14  3   3/14/2014   6
15  3   3/15/2014   6

2 个答案:

答案 0 :(得分:1)

您可以使用窗口函数和算术。以下列举了每个部分中的

select (row_number() over (partition by section order by moment) + 2) / 3, t.*
from @t;

然后应用dense_rank()得到您想要的东西:

select dense_rank() over (order by section, tempcol) as group3,
       t.*
from (select (row_number() over (partition by section order by moment) + 2) / 3 as tempcol, t.*
      from t
     ) t
order by id

Here是db <>小提琴。

答案 1 :(得分:1)

在解释上可能会出错,但是直到我确认这个问题我相信你一直在寻找。我已经使用光标完成了它。希望它对你有帮助。

DECLARE @i int =0 -- row count 
DECLARE @GroupCount int=1 
DECLARE @Id int
DECLARE @Section int
DECLARE @Moment DateTime


declare @temp table (
    SNO int,
    Id      int ,
    Section int,
    Moment  date,
    GroupedIn nvarchar(200)
);
DECLARE db_cursor CURSOR FOR 
SELECT Id,Section,Moment       
FROM @t 
WHERE Section = 3 --suppose 

OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @Id,@Section,@Moment  

WHILE @@FETCH_STATUS = 0  
BEGIN  
Set @i=@i+1

Insert into @temp values(@i,@Id,@Section,@Moment,'G'+CONVERT(nvarchar(20),@GroupCount))
      FETCH NEXT FROM db_cursor INTO @Id,@Section,@Moment   
END 

CLOSE db_cursor  
DEALLOCATE db_cursor 

Select * from @temp