1

我有一个有 5 列的表:

PK_Column, FK_MeterID, Date, Index, Value

我有这个工作正常的查询:

SELECT FK_MeterID,
       sum(Value) as 'Total',
       @p_Month,
       @p_Year
FROM ValuesHistory
WHERE month(Date) = @p_Month
      and year(Date)  = @p_Year
GROUP BY  FK_MeterID

但是,我不想将一个月的值相加,而是

月的最后一个索引和月的第一个索引之间的索引差异

月。(它应该返回相同的结果)

如何使用差异进行此查询?

谢谢

4

1 回答 1

1

听起来好像您正在寻找聚合函数

WITH CTE AS
(
    SELECT RN = ROW_NUMBER() OVER (
                  PARTITION BY FK_MeterID
                  ORDER BY Date, PK_Column),
           TOTAL  = SUM(Value) OVER (PARTITION BY FK_MeterID),
           MINVAL = MIN(Value)  OVER (PARTITION BY FK_MeterID),
           MAXVAL = MAX(Value)  OVER (PARTITION BY FK_MeterID),
           PK_Column, FK_MeterID, [Date], [Index], Value
    FROM ValuesHistory
    WHERE month(Date) = @p_Month
      AND year(Date)  = @p_Year
)
SELECT DIFFERENCE = MAXVAL - MINVAL, CTE.*
FROM CTE
于 2013-05-06T07:56:39.000 回答