如何将 Pivot 与 RowNumber 和日期一起使用

How to use Pivot with RowNumber and date

我有一个 SQL 服务器 table 是这样的:

如何根据行号将阅读列更改为 2 列?

我试过这样:

WITH pivot_data AS
(
    SELECT 
        date, CurrentMeterSNID,
        1 + ((ROW_NUMBER() OVER (PARTITION BY CurrentMeterSNID ORDER BY date desc) - 1) % 2)  rownum,
        Reading
    FROM 
        INF_Facility_ElectricalRecord 
)
SELECT 
    date, CurrentMeterSNID, [1], [2]
FROM 
    pivot_data 
PIVOT 
    (MAX(Reading) FOR rownum IN ([1], [2])) AS p;

但我得到的结果是:

我得到空记录;如何用日期后一天的记录替换该空值?

只要您在该查询中显示每个日期,就无法得到您想要的结果。 所以你必须选择 max(date) 换句话说行号将为 1.

WITH pivot_data AS(
   SELECT date,CurrentMeterSNID,
   1 + ((row_number() over(partition by CurrentMeterSNID ORDER by date desc) - 1) % 2)  rownum,
   Reading
   FROM dbo.Table_1 )
   , T2 AS
   (
SELECT CurrentMeterSNID, date, [1], [2]

FROM pivot_data PIVOT (max(Reading) FOR rownum IN ([1],[2])) AS p
)

SELECT CurrentMeterSNID,  Max(date), MAX([1]), Max([2]) 
FROM T2
GROUP BY CurrentMeterSNID

实际上你没有做 PIVOT。您只想有条件地在不同列上显示值。为此,您使用 CASE 语句。

对于第二个需求:对于NULL值,显示后一天的值,可以使用LEAD() or LAG() window函数。这是 case

else 部分
select  date, CurrentMeterSNID,
        [1] = case when rownum2 = 1 
                   then reading 
                   else lead(reading) over(partition by CurrentMeterSNID order by date)
                   end,
        [2] = case when rownum2 = 2 
                   then reading 
                   else lead(reading) over(partition by CurrentMeterSNID order by date)
                   end
from    INF_Facility_ElectricalRecord