逐月增加每个客户的使用量

时间:2016-07-22 08:39:12

标签: sql sql-server

我有下表:

DECLARE @MyTable TABLE (
    CustomerName nvarchar(max),
    [Date] date,
    [Service] nvarchar(max),
    UniqueUsersForService int
)

INSERT INTO @MyTable VALUES
('CompanyA', '2016-07-14', 'Service1', 100),
('CompanyA', '2016-07-15', 'Service1', 110),
('CompanyA', '2016-07-16', 'Service1', 120),
('CompanyA', '2016-07-14', 'Service2', 200),
('CompanyA', '2016-07-15', 'Service2', 220),
('CompanyA', '2016-07-16', 'Service2', 500),
('CompanyB', '2016-07-14', 'Service1', 10000),
('CompanyB', '2016-07-15', 'Service1', 10500),
('CompanyB', '2016-07-16', 'Service1', 11000),
('CompanyB', '2016-07-14', 'Service2', 200),
('CompanyB', '2016-07-15', 'Service2', 300),
('CompanyB', '2016-07-16', 'Service2', 300)

基本上,它是一个列表,显示每个公司使用每项服务的人数。例如,在CopmanyA中,在14th of July上,有100位唯一身份用户Service1。实际的表包含数千个客户,日期可追溯到2015年1月1日。

我一直在网上搜索能够计算每位客户每项服务的月使用量增量的方法。到目前为止我设法做了什么:我按月分组日期。

例如,日期7/14/2016201607(2016年第7个月),并选择了相应月份的最大使用量。所以现在我需要弄清楚如何计算6月到7月之间的使用差异。

以某种方式从7月份减去6月份的使用量。等等每个月。最终目标是确定使用量增幅最大的客户 - 按百分比计算。我希望能够查看数据并说明 CompanyA在3月份使用了100个许可证,并且在4月份他跳到了1000个。这增加了1000%

我为我提出问题的方式道歉,我对SQL和编码非常陌生,我提前感谢你提供的任何帮助。

2 个答案:

答案 0 :(得分:0)

如果您使用的是SQL Server 2012(及以上版本),则可以使用LAG功能:

;WITH cte AS (
SELECT  CustomerName,
        LEFT(REPLACE(CONVERT(nvarchar(10),[Date],120),'-',''),6) as [month],
        [Service],
        MAX(UniqueUsersForService) as MaxUniqueUsersForService
FROM @MyTable
GROUP BY CustomerName,
        LEFT(REPLACE(CONVERT(nvarchar(10),[Date],120),'-',''),6),
        [Service]
)

SELECT  *, 
        LAG(MaxUniqueUsersForService,1,NULL) OVER (PARTITION BY CustomerName, [Service] ORDER BY [month]) as prevUniqueUsersForService
FROM cte
ORDER BY CustomerName, [month], [Service]

在SQL Server 2008中:

;WITH cte AS (
SELECT  CustomerName,
        LEFT(REPLACE(CONVERT(nvarchar(10),[Date],120),'-',''),6) as [month],
        [Service],
        MAX(UniqueUsersForService) as MaxUniqueUsersForService
FROM @MyTable
GROUP BY CustomerName,
        LEFT(REPLACE(CONVERT(nvarchar(10),[Date],120),'-',''),6),
        [Service]
)

SELECT c.*,
        p.MaxUniqueUsersForService as prevUniqueUsersForService
FROM cte c
OUTER APPLY (SELECT TOP 1 * FROM cte WHERE CustomerName = c.CustomerName AND [Service] = c.[Service] and [month] < c.[month]) as p

答案 1 :(得分:0)

如果您使用的是SQL Server 2012或更高版本,请尝试以下操作:

SELECT *
, CASE 
    WHEN uniqueUsersPrevMonth = 0 THEN uniqueUsersInMonth
    ELSE CAST(uniqueUsersInMonth - uniqueUsersPrevMonth as decimal) / uniqueUsersPrevMonth * 100
    END AS Increase
FROM (
    SELECT customer, service, DATEPART(MONTH, [date]) as [month]
    , SUM(uniqueUsers) AS uniqueUsersInMonth
    , LAG(SUM(uniqueUsers),1,0) OVER(PARTITION BY customer, service ORDER BY  DATEPART(MONTH, [date])) as uniqueUsersPrevMonth
    FROM @tbl AS t
    GROUP BY customer, service, DATEPART(MONTH, [date])
) AS t1
ORDER BY customer, service, [month]
相关问题