使用Group By获取所需结果

时间:2014-11-20 08:13:04

标签: sql sql-server sql-server-2008 mysqli

我有一张桌子"表1"如下所示:

EffectiveDate  Client  Fund    RunDate     UserId 
2014-05-31       A     AGG    2014-06-03    user   
2014-03-31       A     AGG    2014-07-01    user 
2014-10-31       A     AGG    2014-11-04    user 
2014-09-30       A     EFA    2013-10-10    user 
2014-11-31       A     EFA    2014-01-15    user
2014-01-31       A     EFA    2014-02-03    user

我需要获得结果,如果有效日期是任何给定输入日期的最大值,那么它只会返回特定基金的记录。我正在使用查询来获得所需的结果,如:

SELECT Max(tbl.effectivedate) AS EffectiveDate, 
       tbl.client, 
       tbl.fund, 
       tbl.rundate, 
       tbl.userid 
FROM   (SELECT effectivedate, 
               client, 
               fund, 
               rundate, 
               userid 
        FROM   Table1 
        WHERE  effectivedate < = '11/01/2014') AS tbl 
GROUP  BY tbl.client, 
          tbl.fund, 
          tbl.rundate, 
          tbl.userid 

但我没有得到理想的结果。如果有人帮助我,请。

期望的输出:

 EffectiveDate  Client  Fund    RunDate     UserId 
  2014-10-31       A     AGG    2014-11-04    user 
  2014-09-30       A     EFA    2013-10-10    user 

2 个答案:

答案 0 :(得分:2)

试试这个:

示例数据

create table #table1(
    EffectiveDate date,
    Client varchar(100),
    Fund varchar(100),
    RunDate date,
    UserId varchar(100)
)

insert into #table1
select '2014-05-31', 'A', 'AGG', '2014-06-03', 'user' union all 
select '2014-03-31', 'A', 'AGG', '2014-07-01', 'user' union all 
select '2014-10-31', 'A', 'AGG', '2014-11-04', 'user' union all 
select '2014-09-30', 'A', 'EFA', '2013-10-10', 'user' union all 
select '2014-11-30', 'A', 'EFA', '2014-01-15', 'user' union all 
select '2014-01-31', 'A', 'EFA', '2014-02-03', 'user'

CTE解决方案

;with cte as(
    select
        *,
        rn = row_number() over(partition by Fund order by EffectiveDate desc)
    from #table1
    where
        EffectiveDate <= '2014/11/01'
)
select
    EffectiveDate,
    Client,
    Fund,
    RunDate,
    UserId
from cte
where
    rn = 1

没有CTE和ROW_NUMBER()

select
    t1.*
from #table1 t1
inner join (
    select
        EffectiveDate = MAX(EffectiveDate),
        Fund
    from #table1
    where
        EffectiveDate <= '2014/11/01'
    group by Fund
) t2
    on t2.fund = t1.fund
    and t2.EffectiveDate = t1.EffectiveDate

答案 1 :(得分:0)

如果您有兴趣,可以采取另一种方式。您几乎就在那里使用原始代码(在此处小提琴:http://sqlfiddle.com/#!3/20926c/9):

SELECT effectivedate,
       client, 
       fund, 
       rundate, 
       userid 
FROM
(
    SELECT MAX(tbl.effectivedate) OVER (PARTITION BY tbl.client, tbl.fund) AS MaxEffDateByClientByFund,
           tbl.effectivedate,
           tbl.client, 
           tbl.fund, 
           tbl.rundate, 
           tbl.userid 
FROM       Table1 tbl
WHERE      effectivedate < = '20141101'
) tbl2
WHERE effectivedate = MaxEffDateByClientByFund;