如何使用带行号和日期的数据透视表

问题描述 投票:0回答:2

我有一个像这样的SQL Server表:

如何根据行号将读取列更改为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;

但我得到的结果是:

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

sql-server sql-server-2017
2个回答
0
投票

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

对于第二个要求:对于NULL值,显示后续日期值,您可以使用LEAD() or LAG()窗口函数。这是elsecase部分

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 

0
投票

只要您在该查询中显示每个日期,就无法拥有所需的日期。所以你必须选择最大值(日期)换句话说,其中rownumber将为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
© www.soinside.com 2019 - 2024. All rights reserved.