sql查询根据月份获取计数和方差百分比

时间:2016-04-05 17:09:35

标签: sql

我有一个表格,其数据类似于以下内容:

column1            column2
Landing Permit     4/5/2015
Landing Permit     4/6/2015
Landing Permit     4/7/2015
Landing Permit     4/5/2014
Landing Permit     4/6/2014
Landing Permit     4/7/2014
Message            4/5/2015
Message            4/6/2015
Message            4/7/2015
Message            4/5/2014
Message            4/6/2014
Message            4/7/2014

我需要根据与column2的15和14差异来计算方差。我想获得类似于以下内容的输出:

        May                    June                 July
               output/variance     output/variance     output/variance
Landing Permit 1/some%               1/some%             1/some%     
Message        1/some%               1/some%             1/some%

我将如何完成这项工作?

1 个答案:

答案 0 :(得分:0)

我会首先使用像这样的自连接匹配列

SELECT
    a.column1
  , a.column2
  , b.column2
FROM
    Test a
JOIN
    Test b 
ON 
    YEAR(a.column2) = YEAR(b.column2)+1
AND MONTH(a.column2) = MONTH(b.column2)
AND DAY(a.column2) = DAY(b.column2)
AND a.column1 = b.column2
WHERE
    YEAR(a.column2) = 2014

在此之后你可以选择你想要的任何东西,并用类似于CTE的东西进行计算。