Link to home
Start Free TrialLog in
Avatar of databarracks
databarracks

asked on

SQL Query Monthly growth percentage increase/decrease

Hi Guys,

I have stumbled across the below query from the internet and would like to know how I can apply it to my SQL query. I am currently using SQL Server 2012.

select
    month, total,
    (total::float / lag(total) over (order by month) - 1) * 100 growth
from (
    select to_char(created_at, 'yyyy-mm') as month, count(user_id) total
    from users
    group by month
) s
order by month;

Open in new window


The link to this code is http://stackoverflow.com/questions/16357876/sql-query-growth-of-users-per-month-in-percentage however it is for Postgres.

Could someone please help me translate this for MS SQL. Please note that I would need to SUM my totals for a month as an account could have multiple transactions within a single month.

Many thanks
Avatar of databarracks
databarracks

ASKER

ASKER CERTIFIED SOLUTION
Avatar of PortletPaul
PortletPaul
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Are you working with SQL Server sysusers view? Because if you do, won't work. That view don't returns deleted users.
Hi Guys,

PortletPaul your query seems to be working correctly:) However I am interested to know I bit more about "multiply that lag() value by 1.0" and why you are suggesting that this may be a problem?

Other than that I think we are onto a winner.
I didn't do any testing I was just "translating" using "the little grey cells"

re:"multiply that lag() value by 1.0"
Normally I multiply the divisor by 1.0  e.g. ([someintvalue] / [someotherinteger] * 1.0) as something
So I wasn't sure if integer math would take over if that wasn't done. If you are getting good results that's fine.

I'm still not sure why that minus one exists though.
Ok great thanks for your help PortletPaul I am happy with the results
PortletPaul is always on the ball :)
thanks, is that a jingle?