2016-01-20 61 views
-1
SELECT RIGHT(timestamp,LEN(timestamp) -12) as DailyTime, left(roundtrip, LEN(roundtrip) -2) as HalfHourDuration, site_code 
FROM tblServer_Status 
WHERE timestamp >= dateadd(day, datediff(day,'19000101',CURRENT_TIMESTAMP),'19000101') AND timestamp < dateadd(day, datediff(day,'19000101',CURRENT_TIMESTAMP)+1,'19000101') AND server = 'ServerName' AND site_code = 'A' 
GROUP BY timestamp, roundtrip, site_code HAVING(((COUNT(site_code))>0)) 
ORDER BY timestamp 

每個時間間隔最新值我有這樣的代碼,讓我這種輸出如何獲得在SQL Server

| DailyTime | HalfHourDuration | Site_Code| 
    12:00AM   122    A 
    12:00AM   143    A 
    12:00AM   242    A 
    12:30AM   112    A 
    12:30AM   222    A 
    12:30AM   462    A 
    01:00AM   322    A 
    01:00AM   642    A 
    01:00AM   322    A 
    01:30AM   146    A 
    01:30AM   167    A 
    01:30AM   116    A 
    02:00AM   163    A 
    02:00AM   145    A 
    02:00AM   121    A 
    02:30AM   149    A 
    02:30AM   135    A 
    02:30AM   111    A 
    ................................... 

,但我需要得到每一次最新的時間。 喜歡這個

| DailyTime | HalfHourDuration | Site_Code| 
    12:00AM   242    A 
    12:30AM   462    A 
    01:00AM   322    A 
    01:30AM   116    A 
    02:00AM   121    A 
    02:30AM   111    A 

就是這樣的。 任何人都可以幫助我配置我的代碼。

謝謝。

回答

0

可以使用row_number()做到這一點:

with t as (
     <your query here without order by> 
    ) 
select t.* 
from (select t.*, 
      row_number() over (partition by DailyTime 
           order by HalfHourDuration desc 
           ) as seqnum 
     from t 
    ) t 
where seqnum = 1; 
+0

夥計。謝謝。但時間的順序是按數字。你能幫我把它按AM - PM排序。 – Elphrian

+0

我需要從12:00 AM到11:30 PM的時間排序。感謝您的答覆。 – Elphrian

0

添加最大功能將您的列HalfHourDuration。 這將列出通過時間戳單獨分組的最大值

+0

我已經試過了,但輸出相同 – Elphrian