0

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

-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
4

1 回答 1

0

我的建议是考虑添加row_number()到您的子查询中。如果您按locationand对数据进行分区order 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

于 2013-10-29T21:01:00.473 回答