同一表上分组行的差异和百分比变化

时间:2018-07-16 18:10:16

标签: sql-server tsql

使用Microsoft SQL Server 2014

使用以下查询:

SELECT DISTINCT  *
INTO #Temp_1
    FROM (
        SELECT *, Row_Number() 
          OVER (PARTITION BY [State]
                ORDER BY [EntryDate] ASC ) AS Row_Number
          FROM [dbo].[OrderAudit] 
            ) AS EntryDates WHERE Row_Number <= 2
          Order by [State] ASC, [EntryDate] Desc

Select * from #temp_1 order by state ASC, entrydate desc

我产生一个像这样的表:

State   EntryDate   Count_1   Count_2   Count_3     ...  Count350

SC      2018-08-05  1000        2000      3000      ...  1000
SC      2018-08-01  1500        2400      3000      ...  1500
TN      2018-04-20  2000        3000      3400      ...  2000
TX      2018-04-20  1500        1000      7000      ...  1500

我想输出:

State  Most_Recent     Elapsed    Count_1_diff   Count_1_%_diff   ... 
SC     2018-08-05      04           500            -33.33
TN     2018-04-20      0            0                 0
TX     2018-04-20      0            0                 0 

我正在尝试做这样的事情:

;WITH rows AS
              (SELECT DISTINCT * , Row_Number() 
               OVER (PARTITION BY [State]
                     ORDER BY [state], [EntryDate] )as rn
               FROM   #temp_1)


        SELECT DISTINCT   mc.[State]
                ,mc.[EntryDate]
                ,DATEDIFF(DAY,mp.EntryDate,mc.EntryDate) AS Elapsed
                ,mc.Count_1 - mp.Count_1 AS Count_1_Diff
                ,STR(ISNULL(((mc.Count_1-mp.Count_1)/NULLIF(CAST(mp.Count_1 AS NUMERIC(10,2)),0)),0) * 100 ,5,2) AS Count_1_%_diff

        INTO #Temp_2
        FROM    rows mc
        JOIN    rows mp
        ON      mc.rn = (mp.rn + 1)

这没有给我我需要的东西,我也不知道如何选择每一列(300个不同的计数)来进行这两个计算而没有全部写出来。

1 个答案:

答案 0 :(得分:0)

更改此:

JOIN    rows mp

对此:

LEFT OUTER JOIN    rows mp

不写出所有列名的唯一方法就是使用动态sql。

相关问题