year to date running total for fiscal year - sql

SELECT DISTINCT
ACCOUNTDATE
,PROPERTYNAME
,rt.management
from aaa t
cross apply
(select SUM(MANAGEMENT) as management
from aaa
where
PROPERTYNAME = t.PROPERTYNAME and
ACCOUNTDATE BETWEEN dateadd(MONTH, datediff(MONTH, 0,t.ACCOUNTDATE),0) -- start of month
AND t.ACCOUNTDATE
) as rt
WHERE AccountDate BETWEEN #STARTOFMONTH_MAN AND #ENDOFMONTH_MAN
ORDER BY AccountDate
This is the query to find month to date.
How to find year to date for fiscal year from the same query?
eg: running total from 01/04/2015-31/03/2016

Not sure from wich date you need the FY start. Suppose from #STARTOFMONTH_MAN. Then you can get FY start as
declare #fymonth int = 4; -- first month of FY.
declare #STARTOFMONTH_MAN date = '20160320';
select fyStart = dateadd(MONTH,
#fymonth - CASE WHEN month(#STARTOFMONTH_MAN) >= #fymonth THEN 1 ELSE 13 END,
dateadd(YEAR, datediff(YEAR, 0, #STARTOFMONTH_MAN),0));
You may simplify those dates calculations by creating calendar table.
EDIT
Idea is to restrict data in WHERE with the larger interval and conditionally SUM data for the subinterval.
declare #fymonth int = 4; -- first month of FY.
SELECT DISTINCT
ACCOUNTDATE
,PROPERTYNAME
,rt.FYManagement, rt.MonthManagement
FROM aaa t
CROSS APPLY
(SELECT
SUM(t2.MANAGEMENT) AS FYManagement
,SUM(CASE WHEN t2.ACCOUNTDATE BETWEEN
-- start of month for t.ACCOUNTDATE
dateadd(MONTH, datediff(MONTH, 0, t3.ACCOUNTDATE), 0)
AND t3.ACCOUNTDATE
THEN t2.MANAGEMENT END) AS MonthManagement
from aaa t2
JOIN aaa t3 ON t3.primarykey = t.primarykey -- change as needed to get 1 to 1 JOIN
where
t2.PROPERTYNAME = t.PROPERTYNAME and
t2.ACCOUNTDATE BETWEEN
-- FY start for t.ACCOUNTDATE
dateadd(MONTH,
#fymonth - CASE WHEN month(t.ACCOUNTDATE) >= #fymonth THEN 1 ELSE 13 END,
dateadd(YEAR, datediff(YEAR, 0, t.ACCOUNTDATE), 0));
AND t.ACCOUNTDATE
) as rt
WHERE AccountDate BETWEEN #STARTOFMONTH_MAN AND #ENDOFMONTH_MAN
ORDER BY AccountDate

declare #fymonth int = 4; -- first month of FY.
SELECT DISTINCT
ACCOUNTDATE
,PROPERTYNAME
,rt.FYManagement, rt.MonthManagement
FROM aaa t
CROSS APPLY
(SELECT
SUM(t2.MANAGEMENT) AS FYManagement
,SUM(CASE WHEN t2.ACCOUNTDATE BETWEEN
-- start of month for t.ACCOUNTDATE
dateadd(MONTH, datediff(MONTH, 0, t3.ACCOUNTDATE), 0)
AND t3.ACCOUNTDATE
THEN t2.MANAGEMENT END) AS MonthManagement
from aaa t2
JOIN aaa t3 ON t3.primarykey = t.primarykey -- change as needed to get 1 to 1 JOIN
where
t2.PROPERTYNAME = t.PROPERTYNAME and
t2.ACCOUNTDATE BETWEEN
-- FY start for t.ACCOUNTDATE
dateadd(MONTH,
#fymonth - CASE WHEN month(t.ACCOUNTDATE) >= #fymonth THEN 1 ELSE 13 END,
dateadd(YEAR, datediff(YEAR, 0, t.ACCOUNTDATE), 0));
AND t.ACCOUNTDATE
) as rt
WHERE AccountDate BETWEEN #STARTOFMONTH_MAN AND #ENDOFMONTH_MAN
ORDER BY AccountDate

Related

Dividing monthly rate between Start and End Dates

I have Monthly rate for each employee in one table which I need to distribute equally based on the Employee Start and End date in the particular project.
For e.g. The monthly rate for employee X is $4300 which is stored in Table A. The employee start & end date in the project is '2017-11-03' & '2017-12-12' respectively and is stored in Table B. I need the employee cost for both Nov and Dec months.
Appreciate any help on this.
Edits:
Table 1:Employee Details
Col1-Employee name
Col2-Start date
Col3- End date
Table 2: Rate Card
Col1-Location
Col2-Grade
Col3- Cost Per Month
Table 3: Employee Billing
Col1-Year
Col2-Month
Col3- Employee
Col4- Cost per month
So if Employee worked from 4-Nov-17 to 31-Dec-17 and Cost per month is $4000, then in Billing table there should be 2 entries like:
2017,Nov,Emp1,(4000/30)*((30-4)+1)
2017,Dec,Emp1,4000
I was ale to insert 2 entries in table 3 based on input from table 1 but not able to calculate the customized cost
case
when (webResource_Details_ESS_recurrent_entries.recurrent_month<>DATEPART(mm, l.start_date) or
webResource_Details_ESS_recurrent_entries.recurrent_month<>DATEPART(mm, l.end_date))
then
l.Employee_Cost
when DATEPART(day, l.start_date) <> 1 and Eomonth(l.start_date) = Eomonth(l.end_date) then
(Datediff(day, l.start_date, l.end_date) *
(l.Employee_Cost / Datediff(day,Eomonth(l.start_date), Dateadd(month,1, Eomonth(l.start_date))) ) )
when DATEPART(day, l.start_date) <> 1 and Eomonth(l.start_date) <> Eomonth(l.end_date) then ( Datediff(day, l.start_date, Eomonth(l.start_date)) *
( l.Employee_Cost /Datediff(day, Eomonth(l.start_date), Dateadd(month, 1,Eomonth(l.start_date))) ) )
when DATEPART(day, l.end_date) <> (DATEPART(day, DATEADD(second,-1,DATEADD(month, DATEDIFF(month,0,l.end_date)+1,0)))) and Eomonth(l.start_date) <> Eomonth(l.end_date) then (Datediff(day, ( Dateadd(month, Datediff(month, 0,l.end_date),0) ),l.end_date)
*(l.Employee_Cost /Datediff(day, Eomonth(l.end_date),Dateadd(month, 1, Eomonth(l.end_date)))))
end as Employee_Cost
SELECT em.employeed,
CASE
WHEN Eomonth(startdate) = Eomonth(enddate)
THEN (Datediff(day, startdate, enddate) *
(rate / Datediff(day,Eomonth(startdate), Dateadd(month,1, Eomonth(startdate))) ) )
ELSE ( ( Datediff(day, startdate, Eomonth(startdate)) *
( rate /Datediff(day, Eomonth(startdate), Dateadd(month, 1,Eomonth(startdate))) ) ) +
(Datediff(day, ( Dateadd(month, Datediff(month, 0,enddate),0) ),enddate)
*(rate /Datediff(day, Eomonth(enddate),Dateadd(month, 1, Eomonth(enddate))))))
END AS wage
FROM employeemaster em
INNER JOIN employeerate AS er
ON ( em.employeed = er.employeed )
First Case will handle case when both start date and end date are in same month
eomonth(startdate) = eomonth(enddate) then (datediff(day,startdate,enddate)*(rate/datediff(day, eomonth(startdate), dateadd(month, 1, eomonth(startdate)))))
This calculate days and rate for month of start date
datediff(day,startdate,eomonth(startdate)) * (rate/datediff(day, eomonth(startdate), dateadd(month, 1, eomonth(startdate)))))
This calculate days and rate for month of end date
(datediff(day,(DATEADD(month, DATEDIFF(month, 0, enddate), 0)),enddate)* rate/datediff(day, eomonth(enddate), dateadd(month, 1, eomonth(enddate))))

Is it possible to add second where condition to select this same data but from other date range?

I have two tables in SQL Server.
I want to select DeptCode, DeptName, YearToDate, PeriodToDate (2 months for example) and group it by DeptCode.
There is a result which I want to get:
In YTD column I want to get sum of totalCost since 01/01/actualYear.
In PTD column I want to get the sum from last two months.
I created a piece of code which shows me correct YTD cost but I don't know how I can add next one for getting total cost for other date range. Is it possible to do this?
SELECT
d.DeptCode,
d.DeptName,
SUM(s.TotalCost) as YTD
FROM [Departments] AS d
INNER JOIN Shipments AS s
ON d.DeptCode= s.DeptCode
WHERE s.ShipmentDate BETWEEN DateAdd(yyyy, DateDiff(yyyy, 0, GetDate()), 0)
AND GETDATE()
GROUP BY d.DeptCode, d.DeptName
Your expected output doesn't match 2 months, but here's the code to accomplish what you want. You just have to add a SUM(CASE...) on the 2nd condition.
SELECT
d.DeptCode,
d.DeptName,
SUM(s.TotalCost) as YTD,
SUM(CASE WHEN s.ShipmentDate >= DATEADD(month, -2, GETDATE()) then s.TotalCost else 0 END) as PTD
FROM [Departments] AS d
INNER JOIN Shipments AS s
ON d.DeptCode= s.DeptCode
WHERE Year(s.ShipmentDate) = Year(GETDATE())
GROUP BY d.DeptCode, d.DeptName
Just add one more column that returns 0 when not in the two-month range, e.g. SUM(CASE WHEN (date check) THEN (amount) ELSE 0 END). Check out the fifth line:
SELECT
d.DeptCode,
d.DeptName,
SUM(s.TotalCost) as YTD,
SUM(CASE WHEN DateDiff(MONTH, s.ShipmentDate, GetDate()) < 2 THEN s.TotalCost ELSE 0 END) PTD,
FROM [Departments] AS d
INNER JOIN Shipments AS s
ON d.DeptCode= s.DeptCode
WHERE s.ShipmentDate BETWEEN DateAdd(yyyy, DateDiff(yyyy, 0, GetDate()), 0)
AND GETDATE()
GROUP BY d.DeptCode, d.DeptName
Try this one :
nbr_last2month_ AS
(
SELECT DISTINCT
Sum(s.[TotalCost]) AS 'PTD',
s.DeptCode,
s.DeptName
FROM [Shipements] s
LEFT JOIN [Departements] d ON d.[DeptCode] = s.[DeptCode]
WHERE Year(date_) LIKE Year(GETDATE())
AND MONTH(ShipementDate) LIKE Month(Getdate()) - 2
Group by DeptCode
),
nbr_YTD_ AS
(
SELECT DISTINCT
Sum(s.[TotalCost]) AS 'YTD',
s.DeptCode,
s.DeptName
FROM [Shipements] s
LEFT JOIN [Departements] d ON d.[DeptCode] = s.[DeptCode]
WHERE Year(ShipementDate) LIKE Year(GETDATE())
Group by DeptCode
),
SELECT
A.DeptCode,
A.DeptName,
YTD,
PTD
FROM nbr_YTD_ A
LEFT JOIN nbr_last2month_ B on B.DeptCode = A.DeptCode
ORDER BY DeptCode

Count number of days each employee take vacation in a month SQL Server

I have this table:
Vacationtbl:
ID Start End
-------------------------
01 04/10/17 04/12/17
01 04/27/17 05/02/17
02 04/13/17 04/15/17
02 04/17/17 04/20/17
03 06/14/17 06/22/17
Employeetbl:
ID Fname Lname
------------------
01 John AAA
02 Jeny BBB
03 Jeby CCC
I like to count the number of days each employee take vacation in April.
My query:
SELECT
SUM(DATEDIFF(DAY, Start, End) + 1) AS Days
FROM
Vacationtbl
GROUP BY
ID
01 returns 9 (not correct)
02 returns 7 (correct)
How do I fix the query so that it counts until the end of month and stops at end of month. For example, April has 30 days. On second row, Employee 01 should counts 4/27/17 until 4/30/17. And 05/02/17 is for May.
Thanks
The Tally/Calendar table is the way to go. However, you can use an ad-hoc tally table.
Example
Select Year = Year(D)
,Month = Month(D)
,ID
,Days = count(*)
From Vacationtbl A
Cross Apply (
Select Top (DateDiff(DAY,[Start],[End])+1) D=DateAdd(DAY,-1+Row_Number() Over (Order By (Select Null)),[Start])
From master..spt_values
) B
-- YOUR OPTIONAL WHERE STATEMENT HERE --
Group By ID,Year(D),Month(D)
Order By 1,2,3
Returns
Year Month ID Days
2017 4 01 7
2017 4 02 7
2017 5 01 2
EDIT - To Show All ID even if Zero Days
Select ID
,Year = Year(D)
,Month = Month(D)
,Days = sum(case when D between [Start] and [End] then 1 else 0 end)
From (
Select Top (DateDiff(DAY,'05/01/2017','05/31/2017')+1) D=DateAdd(DAY,-1+Row_Number() Over (Order By (Select Null)),'05/01/2017')
From master..spt_values
) D
Cross Join Vacationtbl B
Group By ID,Year(D),Month(D)
Order By 1,2,3
Returns
ID Year Month Days
1 2017 5 2
2 2017 5 0
dbFiddle if it Helps
EDIT - 2 Corrects for Overlaps (Gaps and Islands)
--Create Some Sample Data
----------------------------------------------------------------------
Declare #Vacationtbl Table ([ID] varchar(50),[Start] date,[End] date)
Insert Into #Vacationtbl Values
(01,'04/10/17','04/12/17')
,(01,'04/27/17','05/02/17')
,(02,'04/13/17','04/15/17')
,(02,'04/17/17','04/20/17')
,(02,'04/16/17','04/17/17') -- << Overlap
,(03,'05/16/17','05/17/17')
-- The Actual Query
----------------------------------------------------------------------
Select ID
,Year = Year(D)
,Month = Month(D)
,Days = sum(case when D between [Start] and [End] then 1 else 0 end)
From (Select Top (DateDiff(DAY,'04/01/2017','04/30/2017')+1) D=DateAdd(DAY,-1+Row_Number() Over (Order By (Select Null)),'04/01/2017') From master..spt_values ) D
Cross Join (
Select ID,[Start] = min(D),[End] = max(D)
From (
Select E.*,Grp = Dense_Rank() over (Order By D) - Row_Number() over (Partition By ID Order By D)
From (
Select Distinct A.ID,D
From #Vacationtbl A
Cross Apply (Select Top (DateDiff(DAY,A.[Start],A.[End])+1) D=DateAdd(DAY,-1+Row_Number() Over (Order By (Select Null)),A.[Start]) From master..spt_values ) B
) E
) G
Group By ID,Grp
) B
Group By ID,Year(D),Month(D)
Order By 1,2,3
Returns
ID Year Month Days
1 2017 4 7
2 2017 4 8
3 2017 4 0
Without a dates table, you could use
select Id
,sum(case when [end]>'20170430' and [start]<'20170401' then datediff(day,'20170401','20170430')+1
when [end]>'20170430' then datediff(day,[start],'20170430')+1
when [start]<'20170401' then datediff(day,'20170401',[end])+1
else datediff(day,[start],[end])+1
end) as VacationDays
from Vacationtbl
where [start] <= '20170430' and [end] >= '20170401'
group by Id
There are 3 conditions here
Start is before this month and the end is after this month. In this case you subtract the end and start dates of the month.
End is after month end and start is in the month, in this case subtract month end date from the start.
Start is before this month but the end is in the month. In this case subtract month start date and the end date.
Edit: Based on the OP's comments that the future dates have to be included,
/*This recursive cte generates the month start and end dates with in a given time frame
For Eg: all the month start and end dates for 2017
Change the start and end period as needed*/
with dates (month_start_date,month_end_date) as
(select cast('2017-01-01' as date),cast(eomonth('2017-01-01') as date)
union all
select dateadd(month,1,month_start_date),eomonth(dateadd(month,1,month_start_date)) from dates
where month_start_date < '2017-12-01'
)
--End recursive cte
--Query logic is the same as above
select v.Id
,year(d.month_start_date) as yr,month(d.month_start_date) as mth
,sum(case when v.[end]>d.month_end_date and v.[start]<d.month_start_date then datediff(day,d.month_start_date,d.month_end_date)+1
when v.[end]>d.month_end_date then datediff(day,v.[start],d.month_end_date)+1
when v.[start]<d.month_start_date then datediff(day,d.month_start_date,v.[end])+1
else datediff(day,v.[start],v.[end])+1
end) as VacationDays
from dates d
join Vacationtbl v on v.[start] <= d.month_end_date and v.[end] >= d.month_start_date
group by v.id,year(d.month_start_date),month(d.month_start_date)
Assuming you want only one month and you want to count all days, you can do this with arithmetic. A separate calendar table is not necessary. The advantage is performance.
I think this would be easier if SQL Server supported least() and greatest(), but case will do:
select id,
sum(1 + datediff(day, news, newe)) as vacation_days_april
from vactiontbl v cross apply
(values (case when [start] < '2017-04-01' then cast('2017-04-01' as date) else [start] end),
(case when [end] >= '2017-05-01' then cast('2017-04-30' as date) else [end] end)
) v(news, newe)
where news <= newe
group by id;
You can readily extend this to any month:
with m as (
select cast('2017-04-01' as date) as month_start,
cast('2017-04-30' as date) as month_end
)
select id,
sum(1 + datediff(day, news, newe)) as vacation_days_aprile
from m cross join
vactiontbl v cross apply
(values (case when [start] < m.month_start then m.month_start else [start] end),
(case when [end] >= m.month_end then m.month_end else [end] end)
) v(news, newe)
where news <= newe
group by id;
You can even use a similar idea to extend to multiple months, with a different row for each user and each month.
You can use a Calendar or dates table for this sort of thing.
For only 152kb in memory, you can have 30 years of dates in a table with this:
/* dates table */
declare #fromdate date = '20000101';
declare #years int = 30;
/* 30 years, 19 used data pages ~152kb in memory, ~264kb on disk */
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
select top (datediff(day, #fromdate,dateadd(year,#years,#fromdate)))
[Date]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,#fromdate))
into dbo.Dates
from n as deka cross join n as hecto cross join n as kilo
cross join n as tenK cross join n as hundredK
order by [Date];
create unique clustered index ix_dbo_Dates_date
on dbo.Dates([Date]);
Without taking the actual step of creating a table, you can use it inside a common table expression with just this:
declare #fromdate date = '20170401';
declare #thrudate date = '20170430';
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
, dates as (
select top (datediff(day, #fromdate, #thrudate)+1)
[Date]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,#fromdate))
from n as deka cross join n as hecto cross join n as kilo
cross join n as tenK cross join n as hundredK
order by [Date]
)
select [Date]
from dates;
Use either like so:
select
v.Id
, count(*) as VacationDays
from Vacationtbl v
inner join Dates d
on d.Date >= v.[Start]
and d.Date <= v.[End]
where d.Date >= '20170401'
and d.Date <= '20170430'
group by v.Id
rextester demo (table): http://rextester.com/PLW73242
rextester demo (cte): http://rextester.com/BCY62752
returns:
+----+--------------+
| Id | VacationDays |
+----+--------------+
| 01 | 7 |
| 02 | 7 |
+----+--------------+
Number and Calendar table reference:
Generate a set or sequence without loops - 2 - Aaron Bertrand
The "Numbers" or "Tally" Table: What it is and how it replaces a loop - Jeff Moden
Creating a Date Table/Dimension in sql Server 2008 - David Stein
Calendar Tables - Why You Need One - David Stein
Creating a date dimension or calendar table in sql Server - Aaron Bertrand
Try this,
declare #Vacationtbl table(ID int,Startdate date,Enddate date)
insert into #Vacationtbl VALUES
(1 ,'04/10/17','04/12/17')
,(1 ,'04/27/17','05/02/17')
,(2 ,'04/13/17','04/15/17')
,(2 ,'04/17/17','04/20/17')
-- somehow convert your input into first day of month
Declare #firstDayofGivenMonth date='2017-04-01'
Declare #LasttDayofGivenMonth date=dateadd(day,-1,dateadd(month,datediff(month,0,#firstDayofGivenMonth)+1,0))
;with CTE as
(
select *
,case when Startdate<#firstDayofGivenMonth then #firstDayofGivenMonth else Startdate end NewStDT
,case when Enddate>#LasttDayofGivenMonth then #LasttDayofGivenMonth else Enddate end NewEDT
from #Vacationtbl
)
SELECT
SUM(DATEDIFF(DAY, NewStDT, NewEDT) + 1) AS Days
FROM
CTE
GROUP BY
ID

Normalization of Year bringing nulls back

I have the following query:
SELECT DISTINCT
YEAR(DateRegistered) as Years,
Months.[MonthName],
COUNT(UserID)as totalReg
FROM
Months WITH(NOLOCK)
LEFT OUTER JOIN
UserProfile WITH(NOLOCK)
ON
Months.MonthID = MONTH(DateRegistered)
AND
DateRegistered > DATEADD(MONTH, -12,GETDATE())
GROUP BY YEAR(DateRegistered), Months.[MonthName]
ORDER BY Months.[MonthName]
As you can tell this will always bring back 12 months worth of data. As such it is working, although there is a bug with this method.
It creates Null values in months where there is no data, now the record should exist(whole point of the query) but Year field is bringing Nulls which is something I dont want.
Now I understand the problem is because there is no data, how is it supposed to know what year?
So my question is - is there any way to sort this out and replace the nulls? I suspect I will have to completely change my methodology.
**YEAR** **MONTH** **TOTAL**
2013 April 1
2013 August 1
NULL December 0
2013 February 8
2013 January 1
2013 July 1
NULL June 0
2013 March 4
NULL May 0
NULL November 0
NULL October 0
2012 September 3
If you want 12 months of data, then construct a list of numbers from 1 to 12 and use these as offsets with getdate():
with nums as (
select 12 as level union all
select level - 1
from nums
where level > 1
)
select YEAR(thedate) as Years,
Months.[MonthName],
COUNT(UserID) as totalReg
FROM (select DATEADD(MONTH, - nums.level, GETDATE()) as thedate
from nums
) mon12 left outer join
Months WITH (NOLOCK)
on month(mon12.thedate) = months.monthid left outer join
UserProfile WITH (NOLOCK)
ON Months.MonthID = MONTH(DateRegistered) and
DateRegistered > DATEADD(MONTH, -12, GETDATE())
GROUP BY YEAR(thedate), Months.[MonthName]
ORDER BY Months.[MonthName];
I find something strange about the query though. You are defining the span from the current date. However, you seem to be splitting the months themselves on calendar boundaries. I also find the table months to be awkward. Why aren't you just using the datename() and month() functions?
Try this out:
;With dates as (
Select DateName(Month, getdate()) as [Month],
DatePart(Year, getdate()) as [Year],
1 as Iteration
Union All
Select DateName(Month,DATEADD(MONTH, -Iteration, getdate())),
DatePart(Year,DATEADD(MONTH, -Iteration, getdate())),
Iteration + 1
from dates
where Iteration < 12
)
SELECT DISTINCT
d.Year,
d.Month as [MonthName],
COUNT(up.UserID)as totalReg
FROM dates d
LEFT OUTER JOIN UserProfile up ON d.Month = DateName(DateRegistered)
And d.Year = DatePart(Year, DateRegistered)
GROUP BY d.Year, d.Month
ORDER BY d.Year, d.Month
Here's my attempt at a solution:
declare #UserProfile table
(
id bigint not null identity(1,1) primary key clustered
, name nvarchar(32) not null
, dateRegistered datetime not null default(getutcdate())
)
insert #UserProfile
select 'person 1', '2011-01-23'
union select 'person 2', '2013-01-01'
union select 'person 3', '2013-05-27'
declare #yearMin int, #yearMax int
select #yearMin = year(MIN(dateRegistered))
, #yearMax= year(MAX(dateRegistered))
from #UserProfile
;with monthCte as
(
select 1 monthNo, DATENAME(month, '1900-01-01') Name
union all
select monthNo + 1, DATENAME(month, dateadd(month,monthNo,'1900-01-01'))
from monthCte
where monthNo < 12
)
, yearCte as
(
select #yearMin yearNo
union all
select yearNo + 1
from yearCte
where yearNo < #yearMax
)
select y.yearNo, m.Name, COUNT(up.id) UsersRegisteredThisPeriod
from yearCte y
cross join monthCte m
left outer join #UserProfile up
on year(up.dateRegistered) = y.yearNo
and month(up.dateRegistered) = m.monthNo
group by y.yearNo, m.monthNo, m.Name
order by y.yearNo, m.monthNo
SQL Fiddle Version: http://sqlfiddle.com/#!6/d41d8/6640
You have to calculate the counts in a Derived Table (or a CTE) first and then join
untested:
SELECT
COALESCE(dt.Years, YEAR(DATEADD(MONTH, -Months.MonthID, GETDATE()))),
Months.[MonthName],
COALESCE(dt.totalReg, 0)
FROM
Months WITH(NOLOCK)
LEFT OUTER JOIN
(
SELECT
YEAR(DateRegistered) AS Years,
MONTH(DateRegistered) AS Mon,
COUNT(UserID)AS totalReg
FROM UserProfile WITH(NOLOCK)
WHERE DateRegistered > DATEADD(MONTH, -12,GETDATE())
GROUP BY
YEAR(DateRegistered),
MONTH(DateRegistered)
) AS dt
ON Months.MonthID = dt.mon
ORDER BY 1, Months.MonthID
I changed the order to Months.MonthID instead of MonthName and i added year because you might have august 2012 and 2013 in your result.

SQL filter result to current month and previous two months

Here is my sql code:
SELECT Month = datename(month,dateadd(mm,datediff(mm,0,StartTime),0)),
Cast ((ROUND(((CONVERT(DECIMAL(10,2),SUM(Duration)/60)/60)),2)*55) AS numeric(36,2))
FROM VExecutionGlobalHistory Where Tester <> 'dit2988' AND TestTypeID = 1
group by dateadd(mm,datediff(mm,0,StartTime),0), year(dateadd(mm,datediff(mm,0,StartTime),0))
order by dateadd(mm,datediff(mm,0,StartTime),0), year(dateadd(mm,datediff(mm,0,StartTime),0))
This query returns:
April|123
May|3456
June|856
July|345
I want it to return the following:
May|3456
June|856
July|345
Does anyone have any ideas? Im using Microsoft SQL Server Management Studio 2010
The following will return the first day of the month, 2 months back from today:
SELECT CAST(DATEADD(month, DATEDIFF(month, 0, GETDATE())-2, 0)AS DATE)
So you can add to your WHERE criteria:
SELECT Month = datename(month,dateadd(mm,datediff(mm,0,StartTime),0)),
Cast ((ROUND(((CONVERT(DECIMAL(10,2),SUM(Duration)/60)/60)),2)*55) AS numeric(36,2))
FROM VExecutionGlobalHistory
Where Tester <> 'dit2988' AND TestTypeID = 1
AND StartTime >= CAST(DATEADD(month, DATEDIFF(month, 0, GETDATE())-2, 0) AS DATE)
group by dateadd(mm,datediff(mm,0,StartTime),0), year(dateadd(mm,datediff(mm,0,StartTime),0))
order by dateadd(mm,datediff(mm,0,StartTime),0), year(dateadd(mm,datediff(mm,0,StartTime),0))
SELECT TOP 12 b.Month, b.Amount
FROM
(
SELECT TOP 12 a.Year, a.SortMonth, a.Month, a.Amount
FROM
(
SELECT
Year = datename(Year,StartTime),
SortMonth = month(StartTime),
Month = datename(month,dateadd(mm,datediff(mm,0,StartTime),0)),
Amount = Cast ((ROUND(((CONVERT(DECIMAL(10,2),SUM(Duration)/60)/60)),2)*55) AS numeric(36,2))
FROM VExecutionGlobalHistory
Where Tester <> 'dit2988'
AND TestTypeID = 1
group by
datename(Year,StartTime),
month(StartTime),
dateadd(mm,datediff(mm,0,StartTime),0),
year(dateadd(mm,datediff(mm,0,StartTime),0))
) a
ORDER BY a.Year, a.SortMonth DESC
) b
ORDER BY b.Year, b.SortMonth