将数据透视表限制为仅限最近的记录

时间:2013-10-29 20:47:58

标签: sql pivot max

我有一个包含以下字段的表:

-location
-metername
-measurement
-measuredate

我已经向PIVOT写了一个查询,以便metername列中的每个值现在都是它自己的列。但是,我想限制它,使其仅显示基于测量字段的最新仪表读数。有什么建议吗?

SELECT LOCATION, MEASUREDATE, 
    [HEIGHT], [DIAM], [HEIGHT-N], 
    [HEIGHT-W], [HEIGHT-C], [HEIGHT-E], 
    [HEIGHT-S], [DIAM-N], [DIAM-W], 
    [DIAM-C], [DIAM-E], [DIAM-S] 
FROM 
( 
    SELECT LOCATION, MEASUREDATE, METERNAME, MEASUREMENTVALUE 
    FROM MEASUREMENT
) P 
PIVOT 
( 
    SUM(MEASUREMENTVALUE) 
    FOR METERNAME IN ([HEIGHT], [DIAM], [HEIGHT-N], [HEIGHT-W], [HEIGHT-C], 
                        [HEIGHT-E], [HEIGHT-S], [DIAM-N], [DIAM-W], [DIAM-C], 
                        [DIAM-E], [DIAM-S]) 
) AS PVT 
ORDER BY MEASUREDATE DESC

1 个答案:

答案 0 :(得分:0)

我的建议是将row_number()添加到子查询中。如果您按locationorder by measuredate desc对数据进行分区,那么您将为每个位置生成唯一编号,然后您可以按该值过滤数据:

SELECT LOCATION, MEASUREDATE, 
    [HEIGHT], [DIAM], [HEIGHT-N], 
    [HEIGHT-W], [HEIGHT-C], [HEIGHT-E], 
    [HEIGHT-S], [DIAM-N], [DIAM-W], 
    [DIAM-C], [DIAM-E], [DIAM-S] 
FROM 
( 
    SELECT LOCATION, MEASUREDATE, METERNAME, MEASUREMENTVALUE ,
      row_number() over(partition by location
                        order by measuredate desc) seq
    FROM MEASUREMENT
) P 
PIVOT 
( 
    SUM(MEASUREMENTVALUE) 
    FOR METERNAME IN ([HEIGHT], [DIAM], [HEIGHT-N], [HEIGHT-W], [HEIGHT-C], 
                        [HEIGHT-E], [HEIGHT-S], [DIAM-N], [DIAM-W], [DIAM-C], 
                        [DIAM-E], [DIAM-S]) 
) AS PVT 
where seq = 1;

请参阅SQL Fiddle with demo