我在根据数据库中的数据创建趋势时遇到了问题。
我已尝试使用此查询;但需要多个查询。此外,我想知道是否有更好的做法。
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个月前可用的所有记录,以使其成为趋势。
答案 0 :(得分:0)
您可以尝试以下查询
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 强>
<强>更新强>