0

不知道是不是因为我累了,但我似乎无法弄清楚......

我正在寻找一个查询,它将根据几个项目过滤数据......

样本数据:

Business_Month  ID  Calls   Transferred Loaded
11/1/2012 0:00  119118  226 16  12/19/12 15:56
12/1/2012 0:00  119118  333 17  1/15/13 23:54
1/1/2013 0:00   119118  284 6   3/13/13 17:49
1/1/2013 0:00   119118  284 6   3/20/13 13:03
1/1/2013 0:00   119118  284 6   3/20/13 13:25
2/1/2013 0:00   119118  219 8   3/20/13 13:25
3/1/2013 0:00   119118  17  0   3/20/13 13:03
3/1/2013 0:00   119118  17  0   3/20/13 13:25
11/1/2012 0:00  120327  216 13  12/19/12 15:56
12/1/2012 0:00  120327  211 12  1/15/13 23:54
1/1/2013 0:00   120327  255 8   3/13/13 17:49
1/1/2013 0:00   120327  255 8   3/20/13 13:03
1/1/2013 0:00   120327  255 8   3/20/13 13:25
2/1/2013 0:00   120327  166 9   3/20/13 13:25
3/1/2013 0:00   120327  13  2   3/20/13 13:03
3/1/2013 0:00   120327  13  2   3/20/13 13:25

我想要返回的是一行,每个业务月,对于每个具有最高加载日期的唯一 ID...

样本输出:

Business Month  ID  Calls   Transferred Loaded
11/1/2012 0:00  119118  226 16  12/19/12 15:56
12/1/2012 0:00  119118  333 17  1/15/13 23:54
1/1/2013 0:00   119118  284 6   3/20/13 13:25
2/1/2013 0:00   119118  219 8   3/20/13 13:25
3/1/2013 0:00   119118  17  0   3/20/13 13:25
11/1/2012 0:00  120327  216 13  12/19/12 15:56
12/1/2012 0:00  120327  211 12  1/15/13 23:54
1/1/2013 0:00   120327  255 8   3/20/13 13:25
2/1/2013 0:00   120327  166 9   3/20/13 13:25
3/1/2013 0:00   120327  13  2   3/20/13 13:25

我尝试了不同的东西,但似乎无法弄清楚......我正在使用 MS SQL Server......

希望有人可以提供帮助。

谢谢!

4

2 回答 2

1
;WITH x AS 
(
  SELECT [Business_Month], ID, Calls, Transferred, Loaded,
    rn = ROW_NUMBER() OVER 
    (PARTITION BY ID, [Business Month] ORDER BY Loaded DESC)
  FROM dbo.yourtable
)
SELECT [Business Month], ID, Calls, Transferred, Loaded
FROM x
WHERE rn = 1
ORDER BY ID, [Business Month];
于 2013-04-16T01:53:31.430 回答
1

您可以使用子查询来获取max(loaded)每个值business_month,然后将其连接回您的表以获得所需的结果:

select t1.Business_Month,
  t1.ID,
  t1.Calls,
  t1.Transferred,
  t1.Loaded
from yourtable t1
inner join
(
  select Business_Month, 
    max(Loaded) MaxLoaded
  from yourtable
  group by Business_Month
) t2
  on t1.Business_Month = t2.Business_Month
  and t1.Loaded = t2.MaxLoaded
order by t1.id, t1.business_month;

请参阅带有演示的 SQL Fiddle

于 2013-04-16T02:00:39.947 回答