SQL选择最后一组日期?

时间:2013-01-15 16:04:23

标签: sql sql-server sql-server-2008 select group-by

我的表看起来像这样:

Date    DataPoint      Type    Value
2000         HVAC    Phase1      220
2000         HVAC    Phase2      221
2000       SERVER    Phase1      222
2000       SERVER    Phase2      223
2001         HVAC    Phase1      220
2001         HVAC    Phase2      221
2001       SERVER    Phase1      222
2001       SERVER    Phase2      223
2002         HVAC    Phase1      220
2002         HVAC    Phase2      221
2002       SERVER    Phase1      222
2002       SERVER    Phase2      223
...
...
2013         HVAC    Phase1      220
2013         HVAC    Phase2      221
2013       SERVER    Phase1      222
2013       SERVER    Phase2      223

我想获取最后日期,数据点,类型值之和。

预期结果

Date    DataPoint        Value
2013         HVAC          441
2013       SERVER          445

我该怎么做?提示,起点,代码示例?

...谢谢

3 个答案:

答案 0 :(得分:5)

USE TOP... WITH TIES简化:

SELECT TOP 1 WITH TIES Date, DataPoint, SUM(Value) AS Value
FROM YourTable
GROUP BY Date, DataPoint
ORDER BY Date DESC

<强> SQL Fiddle

答案 1 :(得分:3)

您还可以使用子查询获取max(date),然后将其连接回主表:

select t1.date,
  t1.datapoint,
  sum(t1.value) Total
from yourtable t1
inner join
(
  select max(date) date,
    datapoint
  from yourtable
  group by datapoint
) t2
  on t1.date = t2.date
  and t1.datapoint = t2.datapoint
group by t1.date, t1.datapoint;

请参阅SQL Fiddle with Demo

您还可以使用sum() over()row_number() over()来获得结果:

select  Date,  DataPoint, total
from
(
  select Date,
    DataPoint,        
    sum(value) over(partition by DataPoint, Date) total,
    row_number() over(partition by DataPoint order by Date DESC) rn
  from yourtable
) src
where rn = 1

请参阅SQL Fiddle with Demo

结果是:

| DATE | DATAPOINT | TOTAL |
----------------------------
| 2013 |      HVAC |   441 |
| 2013 |    SERVER |   445 |

答案 2 :(得分:1)

WITH latestDate
AS
(
    SELECT  DataPoint, MAX(Date) max_DATE
    FROM tableName
    GROUP BY DataPoint
)
SELECT  a.Date, a.DataPoint, SUM(a.Value) totalValue
FROM    tableName a
        INNER JOIN latestDate b
            ON a.DataPoint = b.DataPoint AND
                a.Date = b.max_date
GROUP BY a.Date, a.DataPoint

感谢SQLFiddle的BlueFeet