用组重复第一个日期

时间:2016-09-19 14:37:24

标签: sql-server sql-server-2012

我希望每个组的第一个日期重复每个组的其余行

enter image description here

4 个答案:

答案 0 :(得分:2)

您可以使用窗口表达式和分组;

FIRST_VALUE (Transact-SQL)

您需要按第一列进行分区。得到A和B的分裂。

例如;

with cteTempData
(
      [Code]
    , [Date]
)
as
(
    select 'A',cast('2015-9-4' as date)
    union all select 'A','2015-9-4'
    union all select 'A','2015-9-4'
    union all select 'A','2015-9-16'
    union all select 'B','2015-9-16'
    union all select 'B','2015-9-22'
    union all select 'B','2015-9-22'
    union all select 'B','2015-10-26'
    union all select 'B','2015-10-30'
)

select
      [Code]
    , [Date]
    , FIRST_VALUE([Date]) over (partition by [Code] order by [Date]) as [First_Date]
from cteTempData

使用first_value语法还允许您使用该有序记录中的其他列....

with cteTempData
(
      [Code]
    , [Date]
    , [Comment]
)
as
(
    select 'A',cast('2015-9-4' as date),'One'
    union all select 'A','2015-9-4','Two'
    union all select 'A','2015-9-4','Three'
    union all select 'A','2015-9-16','Four'
    union all select 'B','2015-9-16','Five'
    union all select 'B','2015-9-22','Six'
    union all select 'B','2015-9-22','Seven'
    union all select 'B','2015-10-26','Eight'
    union all select 'B','2015-10-30','Nine'
)

select
      [Code]
    , [Date]
    , FIRST_VALUE([Date]) over (partition by [Code] order by [Date]) as [First_Date]
    , FIRST_VALUE([Comment]) over (partition by [Code] order by [Date]) as [First_Comment]
from cteTempData

答案 1 :(得分:2)

使用MIN()Over()

Declare @Table table (Grp varchar(25),Date date) 
Insert into @Table values
('A','2015-09-04'),
('A','2015-09-05'),
('A','2015-09-10'),
('B','2015-10-04'),
('B','2015-10-05'),
('B','2015-10-10')

Select *
      ,GrpDate = min(Date) over (Partition By Grp)
 From @Table

返回

Grp Date        GrpDate
A   2015-09-04  2015-09-04
A   2015-09-05  2015-09-04
A   2015-09-10  2015-09-04
B   2015-10-04  2015-10-04
B   2015-10-05  2015-10-04
B   2015-10-10  2015-10-04

答案 2 :(得分:2)

您可以将MINOVER - 子句

一起使用
SELECT t.ColumnA, 
       DateCol = MIN( t.DateCol ) OVER ( PARTITION BY t.ColumnA ),
       OtherColumns
FROM dbo.TableName t

答案 3 :(得分:1)

您可以使用CROSS JOINFIRST_VALUE

Declare @Yourtable table (groupCol varchar(25),firstDate date) 
Insert into @Yourtable values
('A','2015-09-04'),
('A','2015-09-05'),
('A','2015-09-10'),
('B','2015-10-04'),
('B','2015-10-05'),
('B','2015-10-10')

  SELECT a.*,b.firstDate
  FROM @Yourtable a
        CROSS JOIN (SELECT groupCol,MIN(firstDate) firstDate
                    FROM @Yourtable b 
                    GROUP BY groupCol)b 
  WHERE a.groupCol =b.groupCol

OR

SELECT a.*,FIRST_VALUE(a.firstDate) OVER (PARTITION BY groupCol ORDER BY groupCol ASC) AS firstDate 
FROM @Yourtable a