2013-12-15 206 views
5

我有一個名爲MusicTrack的表,其中包含MusicTrackID,TrackName和Duration列。SQL服務器聚合函數查詢

我使用的查詢:

Select Cast(DateAdd(ms,SUM(DateDiff(ms, '00:00:00', Duration)), '00:00:00') as time) 
as 'Total duration' from 
    MusicTrack where MusicTrackID = '1' or MusicTrackID = '3' 

這個查詢增加了2所選音樂的持續時間跟蹤在一起,並將其顯示在名爲總時長一個臨時列。 '持續時間'是數據類型時間,所以我將它轉換爲整數,然後再返回。

我的問題:我能調整查詢的方式還包括TrackName字段和運行總持續時間?或者包括臨時列和TrackName列。

,從而顯示將有TRACKNAME和總時間... ...線沿線的:我想只是包括TRACKNAME列本查詢

TrackName Duration Total duration 

Name1  00:03:00  00:03:00 
Name2  00:03:01  00:06:01 

,但它不工作:

Select TrackName, Cast(....) From MusicTrack where MusicTrackID = '1' or MusicTrackID = '3' 
+1

研究 「運行總計」 中的SQL –

回答

2

嘗試下面

我創建一個試樣臺

SELECT * INTO TMPTIME 
FROM (
SELECT 1 AS ID ,'Name1' AS NAME,'00:03:00' AS T  
UNION 
SELECT 2 AS ID,'Name2' AS NAME,'00:03:01' AS T  
UNION 
SELECT 3 AS ID,'Name3' AS NAME,'00:03:02' AS T 
UNION 
SELECT 4 AS ID,'Name4' AS NAME,'00:03:41' AS T  
)TMP 

輸出查詢

SELECT ID,NAME, T AS TIME, 
(SELECT 
cast(DATEADD(ms, SUM(DATEDIFF(ms, '00:00:00.000', cast (t as time))), '00:00:00.000') as time) 
FROM TMPTIME T1 WHERE T1.ID<=TMPTIME.ID 
) AS TOTAL 

FROM TMPTIME 

結果

ID NAME TIME TOTAL 
1 Name1 00:03:00 00:03:00.0000000 
2 Name2 00:03:01 00:06:01.0000000 
3 Name3 00:03:02 00:09:03.0000000 
4 Name4 00:03:41 00:12:44.0000000 
0

sqlFiddle的SQL Server(不是MySQL的)

SELECT TrackName, Duration, Cast(DateAdd(ms,RunningTotal,'00:00:00') as time) as 'Total Duration' 
FROM 
(SELECT TrackName, Duration, 
    SUM(DateDiff(ms,'00:00:00',Duration)) OVER(ORDER BY MusicTrackId 
    ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) 
     AS RunningTotal 
    FROM MusicTrack 
    WHERE MusicTrackId IN (1,3) 
)T 

語法這裏找到running total

對於MySQL sqlFiddle,(不是SQL Server)的

SELECT TrackName,Date_Format(Duration,'%k:%i:%s') as Duration, 
       Date_Format(runningTotal,'%k:%i:%s') as 'Total Duration' 
FROM 
    (SELECT TrackName, Duration, 
      Sec_To_Time(@total:[email protected] + Time_To_Sec(Duration)) as runningTotal 
    FROM MusicTrack,(SELECT @total:='00:00:00')T 
    WHERE MusicTrackId IN (1,3) 
    ORDER BY MusicTrackId 
)Result