5

我有一个 SQL 2012 查询,它给了我以下结果:

IP_Country  ds          Percentage
-------------------------------------
Australia   01/01/2013  0.70155
Australia   02/01/2013  0.685
Australia   03/01/2013  0.663594
Australia   04/01/2013  0.737541
Australia   05/01/2013  0.688212
Australia   06/01/2013  0.665384
Australia   07/01/2013  0.620253
Australia   08/01/2013  0.697183

结果继续显示相同日期和不同百分比的不同国家。

我需要展示的是,这些百分比仅在同一国家/地区的日期之间变动。

因此,在 02/01 和 01/01 之间,差异为 0.02 - 我可以提取数据并在 excel 中执行此操作,但理想情况下,我希望结果随着查询的移动而出现。

4

3 回答 3

7

您可以使用LAGLEAD访问上一行和下一行。

SELECT *,
        LAG([Percentage]) OVER (PARTITION BY [IP_Country] ORDER BY [ds]) 
                                                               - [Percentage] AS diff,
       ([Percentage] - LEAD([Percentage]) OVER (PARTITION BY [IP_Country] ORDER BY [ds])) 
                                                             / [Percentage] AS [ratio]
FROM  YourTable  

SQL小提琴

于 2013-02-06T13:04:10.277 回答
2

使用CTE和 @MartinSmith 的小提琴(DEMO)。(注意:为了更好的可读性,我已经格式化了 [ds] 日期)

;with cte as (
  select [IP_Country], [ds], [Percentage],
         row_number() over (partition by [IP_Country] order by ds) rn
  from YourTable
)
select t1.[IP_Country], convert(date, t1.[ds],102), 
       t1.[Percentage], t2.[Percentage]-t1.[Percentage] movement
from cte t1 left join cte t2 on t1.[IP_Country] = t2.[IP_Country]
          t1.rn - 1 = t2.rn

--Results
IP_COUNTRY  COLUMN_1    PERCENTAGE  MOVEMENT
Australia   2013-01-01  0.70155     (null)
Australia   2013-02-01  0.685       0.01655
Australia   2013-03-01  0.663594    0.021406
Australia   2013-04-01  0.737541    -0.073947
Australia   2013-05-01  0.688212    0.049329
Australia   2013-06-01  0.665384    0.022828
Australia   2013-07-01  0.620253    0.045131
Australia   2013-08-01  0.697183    -0.07693
于 2013-02-06T14:56:43.080 回答
0

OUTER APPLY 和 EXISTS 的另一种选择

SELECT *, t1.Percentage - o.Percentage AS dif
FROM dbo.test36 t1 
OUTER APPLY (
             SELECT t2.Percentage
             FROM dbo.test36 t2
             WHERE t1.IP_Country = t2.IP_Country 
               AND EXISTS (
                           SELECT 1
                           FROM dbo.test36 t3
                           WHERE t1.IP_Country = t3.IP_Country AND t1.ds < t3.ds
                           HAVING MIN(t3.ds) = t2.ds
                           )
             ) o

SQLFiddle上的演示

于 2013-02-06T15:50:25.530 回答