1

我的桌子看起来像这样:

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

我怎样才能做到这一点?提示,起点,代码示例?

谢谢...

4

3 回答 3

5

用于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小提琴

于 2013-01-15T16:07:38.537 回答
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

您还可以使用sum() over()androw_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

结果是:

| DATE | DATAPOINT | TOTAL |
----------------------------
| 2013 |      HVAC |   441 |
| 2013 |    SERVER |   445 |
于 2013-01-15T16:08:04.430 回答
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

感谢BlueFeet的 SQLFiddle。

于 2013-01-15T16:08:49.127 回答