這似乎更適合您的表示層,但可以使用SQL編寫它。像這樣的東西應該工作使用UNION ALL
每組返回最後一個記錄:
SELECT Name, Dt, Value
FROM (
SELECT Name, Dt, Value, Name Name2
FROM YourTable
UNION ALL
SELECT '' Name, 'Last_Value', T.Value, T.Name Name2
FROM YourTable T
JOIN (
SELECT Name, MAX(dt) MaxDt
FROM YourTable
GROUP BY Name
) T2 ON T.Name = T2.Name AND T.dt = T2.MaxDt
ORDER BY Name2, Dt, Value
) t
SQL Fiddle Demo
結果造成:
NAME DT VALUE
A 2013-01-01 00:00:00 3
A 2013-01-02 00:00:00 4
Last_Value 4
B 2013-01-04 00:00:00 2
B 2013-01-05 00:00:00 8
Last_Value 8
編輯:爲了得到總結集團總,你必須介紹使用用戶定義的變量。下面是一個例子:
SELECT Name, Dt, IF(Name='',summedTotal,Value) Value
FROM (
SELECT @summedTotal:=IF(@prevRow=Name,@summedTotal+Value,Value) summedTotal,
Name, Dt, Value, Name Name2,
@prevRow:=Name
FROM YourTable
JOIN (SELECT @summedTotal:=0) t
UNION ALL
SELECT summedTotal, '' Name, 'Last_Value', T.Value, T.Name Name2, pr
FROM (
SELECT @summedTotal:=IF(@prevRow=Name,@summedTotal+Value,Value) summedTotal,
Name, Dt, Value, Name Name2,
@prevRow:=Name pr
FROM YourTable
JOIN (SELECT @summedTotal:=0) t
) T
JOIN (
SELECT Name, MAX(dt) MaxDt
FROM YourTable
GROUP BY Name
) T2 ON T.Name = T2.Name AND T.dt = T2.MaxDt
ORDER BY Name2, Dt, Value
) t
而更SQL Fiddle
[SQL] SELECT米FROM MYTABLE * AS米INNER JOIN(SELECT MAX(ID)FROM MYTABLE GROUP BY名稱)AS升ON l.id。 = m.id [Err] 1054 - 'on子句'中的未知列'l.id' – 2013-03-16 02:22:26