SQL Select, Specific Rows based on multiple conditions?

走远了吗. 提交于 2020-01-06 07:51:34

问题


Not sure if it's because I'm tired, but I can't seem to figure this out...

I'm looking for a Query that will filter the data based on a couple items...

Sample Data:

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

What I would like returned, is one line, Per Business month, for each unique ID with the highest Loaded Date...

Sample Output:

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

I've tried different things, but can't seem to figure it out... I'm using MS SQL Server...

Hopefully someone can help.

Thanks!


回答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];



回答2:


You can use a subquery to get the max(loaded) value for each business_month and then join that back to yourtable to get the desired result:

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;

See SQL Fiddle with Demo



来源:https://stackoverflow.com/questions/16027485/sql-select-specific-rows-based-on-multiple-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!