SQL - 基于使用情况和月份的趋势

SQL - Trending based on usage and month

我在根据数据库中的数据创建趋势时遇到问题。

我试过使用这个查询;但需要多次查询。此外,我想知道是否有更好的做法来做到这一点。

SELECT DISTINCT TOP 1
    billing.Accounts,
    billing.LastUsage,
    billing.CurrentUsage,
    billing.Total,
    billing.TIME AS Issued

FROM billing
    WHERE
        billing.TIME >= '2016-01-01'
    AND
        billing.TIME <= '2016-04-03'
    AND [top usage account]

ORDER BY
    billing.Total DESC

这是我的数据库布局:

ID      Accounts    LastUsage   CurrentUsage    Total       TIME
----    --------    ---------   ------------    ------      -------
1       26 [FK]         150             200         50      2016-02-01 HH:mm:ss
2       26 [FK]         200             500        300      2016-03-23 HH:mm:ss
3       26 [FK]         500             800        300      2016-04-05 HH:mm:ss
4       27 [FK]           0             250        250      2016-04-05 HH:mm:ss
5       27 [FK]         800            1200        400      2016-06-05 HH:mm:ss

我想要实现的目标

首先,我想知道哪个是重度用户,基于这一个月的使用情况,之后它将检索前 3 个月前可用的所有记录,以使其成为趋势。

您可以试试下面的查询

select TOP 3 
    month(b1.time) monthnum,
    sum(total) monthlyusage
from billing b1 right join
    (
    select 
        top 1 Accounts, month(Time) monthnum from billing 
    where 
        --if using current datetime then use the commented portion below
        eomonth(Time)=eoMONTH(getdate()) 
        --Time >= '2016-01-01' AND TIME <= '2016-04-03'
    order by 
        sum(Total) over(partition by Accounts, month(Time) order by Accounts) desc
    ) b2
    on b1.Accounts=b2.Accounts 
group by month(b1.time)
order by month(b1.time)

SQL fiddle demo

更新

查看我的 sql fiddle 结果