SQL查询min startdate max enddate跨多行

时间:2017-01-25 01:13:19

标签: sql sql-server-2008-r2

SQL Server 2008 R2

我有这样的数据:

+---------+--------+-------------+-------------+
| SchedId |  AdId  |  StartDate  |   EndDate   |
+---------+--------+-------------+-------------+
| 335779  | 179911 | 2017-01-04  | 2017-01-04  |
| 335780  | 179911 | 2017-01-05  | 2017-01-05  |
| ...     |        |             |             |
| 335802  | 179911 | 2017-01-31  | 2017-01-31  |
+---------+--------+-------------+-------------+

对于AdId为179911的所有记录,我需要最低StartDate(2017-01-04)和最大EndDate(2017-01-31)一个特定的日期。

我想将特定日期所需的数据放入临时表中。我试过这个:

declare @dt datetime
set @dt = '2017-01-19'

SELECT  
    MIN(dbo.aoadrundates.StartDate) AS MinStartDate,
    MAX(dbo.aoadrundates.EndDate) AS MaxEndDate,
    dbo.aoadrundates.AdId AS T_AdId
FROM
    dbo.aoadrundates 
WHERE
    StartDate >= @dt AND EndDate <= @dt
GROUP BY
    dbo.AoAdRunDates.AdId,
    dbo.aoadrundates.StartDate,
    dbo.aoadrundates.EndDate

但我只获得了我选择的日期的单一记录,例如

MinStartDate    MaxEndDate  T_AdId
2017-01-19      2017-01-19  179911

我尝试了一些例子,我发现使用cast,min,max以及带有内连接的子查询,但是这些都没有用(我认为),因为我需要从1行分钟和从另一行分配最大值。 / p>

如果你真的不想帮助我,那就好了。如果你能提供帮助,我将非常感激。谢谢

1 个答案:

答案 0 :(得分:0)

问题在于,您要按照dbo.aoadrundates.StartDatedbo.aoadrundates.EndDate按照要汇总的字段进行分组。假设您想要按AdId分组,您可以使用:

declare @dt datetime
set @dt = '2017-01-19'

SELECT  min(dbo.aoadrundates.StartDate) as MinStartDate,
        max(dbo.aoadrundates.EndDate)   as MaxEndDate,
        dbo.aoadrundates.AdId
from 
    dbo.aoadrundates 
    where StartDate >= @dt and EndDate <= @dt
group by
dbo.AoAdRunDates.AdId

从评论&#34;所有记录&#34;虽然您可能希望对AdId的每条记录重复此操作,但在这种情况下,您将不得不使用CTE或类似的(in 2012+ there are better ways ...):

declare @dt datetime
set @dt = '2017-01-19'

;with cte_MinAndMax as (
    SELECT  min(dbo.aoadrundates.StartDate) as MinStartDate,
            max(dbo.aoadrundates.EndDate)   as MaxEndDate,
           dbo.aoadrundates.AdId
    from 
        dbo.aoadrundates 
        where StartDate >= @dt and EndDate <= @dt
    group by
    dbo.AoAdRunDates.AdId
)
select
    dbo.aoadrundates.AdId as T_AdId,
    cte_MinAndMax.MinStartDate,
    cte_MinAndMax.MaxEndDate,
    dbo.aoadrundates.whatever_else_you_want_to_select
from dbo.aoadrundates
left join cte_MinAndMax on dbo.aoadrundates.AdId = cte_MinAndMax.AdId