我有一个包含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
然而,我想做
,而不是将值超过一个月月份的最后一个索引与
的第一个索引之间的索引差异月。 (它应该返回相同的结果)
如何使用差异进行此查询?
由于
答案 0 :(得分:0)
听起来好像在寻找aggregate functions。
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