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

时间:2019-03-25 02:19:27

标签: sql-server sql-server-2017

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

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;

但是我得到的结果是:

Result-Image

我得到空记录;如何从日期后的第二天开始用记录替换空值?

2 个答案:

答案 0 :(得分:0)

只要您在该查询中显示每个日期,就无法获得所需的内容。 因此,您必须选择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

答案 1 :(得分:0)

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

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

case部分
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