这似乎更适合您的表示层,但可以使用 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 小提琴演示
导致:
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