2013-04-16 60 views
0

不知道這是因爲我累了,但我似乎無法想出解決辦法...SQL根據多個條件選擇特定行?

我正在尋找一個查詢,將基於幾個項目篩選數據...

樣本數據:

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 ...

希望有人可以提供幫助。

謝謝!

+0

你可以分享你有沒有試過? – Nunser

回答

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]; 
+0

工作完美!謝謝! – Nortron

1

您可以使用子查詢來獲取每個business_monthmax(loaded)值,然後加入該回yourtable以獲得期望的結果:

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 with Demo