Count within a time period - sql-server

For a helpdesk application we have opened date, closed date, technician name.
Using sql server how can I create a query to show by month and over multiple years:
how many jobs were closed for each month?
for the last day of the month how many jobs were in the queue as unclosed, by technician name?
average number of days to close a job by month by technician name?
Thanks

The query you require is a very simple SQL statement using the GROUP BY clause. Because you are asking information that needs grouping by date only and also information that needs grouping by date and by technician you should use GROUPING SETS.
select year(closed) as year
, month(closed) as month
, Technician
, count(*) as count
, avg(datediff(DAY,Opened, Closed)) as avgDays
from jobs
where not Closed is null
group by grouping sets
(
(year(closed), month(Closed)),
(year(closed), month(Closed), technician)
)
order by year(closed)
, month(closed)
, Technician
If you want the jobs that are not closed remove the NOT in the WHERE clause.

This is a partial answer using a helper table with the first day of every month in a date field. This doesn't give by technician grouping but does calculate 'pending jobs'
select date,
(select COUNT(1) FROM dbo.TASKS WHERE
OPENDATE<=date AND
(CLSDDATE>=date Or CLSDDATE is null))as 'Pending jobs',
(select COUNT(1) FROM dbo.TASKS WHERE
month(CLSDDATE)=MONTH(date) AND YEAR(clsddate)=YEAR(date)) as 'Completed jobs',
(select AVG(datediff(DAY,OPENDATE, CLSDDATE)) as avgDays FROM dbo.TASKS WHERE
month(CLSDDATE)=MONTH(date) AND YEAR(clsddate)=YEAR(date)) as 'AvgDays'
from dbo.CalendarMonths
where date<=GETDATE()

Related

Creating Attendance Report with SSRS

I am trying to create a Attendance result set in SQL Server for using it in a SSRS report. The Employee Attendance table is as below:
EmpId
ADate
In
Out
1
2023-01-01
8:00
15:00
I need to calculate the Total working days for all months in a year and display the number of working days per employee. Report format should be as follows:
Saturday and Sunday being weekend, I can able to get the no of working days monthly.
Another table tbl_Holiday has entries for holidays Fromdate and ToDate. I need to consider that also when calculating working days. Several number of results i got from the internet for calculating this. But when creating a view using this data , it has to calculate workdays for each employee row
SELECT
EmpName, EmpId,
(SELECT COUNT(*) FROM tbl_EmpAttendance
WHERE EmpRecId = A.RecId
GROUP BY MONTH(Adate), YEAR(Adate)) AS WorkedDays,
dbo.fn_GetWorkDays(DATEFROMPARTS(YEAR(ADate), MONTH(ADate), 1), EOMONTH(ADate)) AS workingDays
FROM
tbl_Employee A
LEFT JOIN
tbl_EmpAttendance B ON A.RecId = B.EmpRecId
fn_GetWorkDays - calculates the working days for month.
I need to get number of holidays from tbl_holiday too, I understand that this query is becoming more complex than I thought. There must be simpler way to achieve this, can anyone please help?
I tried to get the result in one single view, for using that as SSRS report dataset

SQL Server - Aggregate previous 5 months sales data to current month [duplicate]

This question already has answers here:
Rolling sum previous 3 months SQL Server
(3 answers)
Closed 4 years ago.
I need to aggregate sales of previous five months to current month for each record. In the table below for example,
StoreID |Month |Sales
-----------|----------|----------
119119 |201802|50000
119119 |201803|62500
119119 |201804|93750
119119 |201708|45000
119271 |201803|25000
119271 |201804|75000
119271 |201802|50000
StoreID 119119's aggregated sales for Month 201804 should be 50000+62500+93750.
Aggregated sales for 119119 for Month 201803 should be 62500+50000 and so on.
I need to do this so that I will be able to plot this aggregated column on a time-series graph.
I cannot use ASC ROWS 5 PRECEEDING here because there may not be sales data for every month and I should not aggregate previous 5 records but it should be strictly based on previous 5 months sales data.
Is it possible to do this without using cursors? Can someone suggest a solution?
You can use a self join to get the older values. ie:
DECLARE #stores TABLE(StoreID INT, [Month] VARCHAR(6), Sales INT);
INSERT INTO #stores(StoreID, Month, Sales)
VALUES(119119, '201802', 50000),
(119119, '201803', 62500),
(119119, '201804', 93750),
(119119, '201708', 45000),
(119271, '201803', 25000),
(119271, '201804', 75000),
(119271, '201802', 50000);
WITH
Sales AS (SELECT StoreID, CAST([Month]+'01' AS DATE) AS [Month], Sales FROM #stores)
SELECT s1.StoreID, s1.[Month], SUM(s2.Sales) AS total
FROM Sales s1
inner JOIN Sales s2 ON s1.StoreID=s2.StoreID
AND s1.[Month]>=s2.[Month]
AND DATEDIFF(MONTH, s2.[Month], s1.[Month])<5
GROUP BY s1.StoreID, s1.[Month]
ORDER BY s1.StoreID, s1.[Month];

SQL Server Group data by week but show the start of the week

I have a query to select customer data and I want to keep an evolution of the number of customers. In week 1 I have 2 new customers so the number is 2. In week 2 I receive 3 new customers, so the number of customers is 5.
I have following query to do this
SELECT LAST_UPDATED_WEEK, SUM( NUM_CUSTOMERS ) OVER ( ORDER BY LAST_UPDATED_WEEK ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS "Number of customers"
FROM (
SELECT DATEADD(dd,DATEDIFF(dd,0,REGISTRATION_DATE),0) AS LAST_UPDATED_WEEK,
COUNT(DISTINCT CUSTOMER_ID) AS NUM_CUSTOMERS
FROM CUSTOMERS_TABLE
GROUP BY DATEADD(dd,DATEDIFF(dd,0,REGISTRATION_DATE),0)) AS T
But when I run this query, it doesn't group my data by week. I read about a DATEPART function, but that returns an integer, but I need to have the actual date.
Can someone help me?
Just replace dd in DATEADD and DATEDIFF functions with WEEK

SQL Server Amount "Open" At Each Month End

I need to create a query that will sum the Amount of Open Accounts Receivable for each month.
Each record in my table has Amount,Posting Date, and Closed at Date. So for example, one record might be: Amount : 5000, Posting Date : 1/1/15, Closed at Date : 3/5/15. So for this record, the 5000 would need to be added to my January Open AR calculation because it is open as of 1/31/15, added to my February Open AR calculation because it is open as of 2/28/15, but excluded from my March Open AR calculation because it is closed as of 3/31/15.
I have managed to create a query that will work for an individual month, given a single inputted month-end date, i.e. 1/31/15 or 2/28/15, etc..., which goes into the WHERE clause.
SELECT SUM(Amount), threemonthavg, SUM(Amount)/threemonthavg AS DSO
FROM tbl1
WHERE PostDate <= #enddate AND ClosedDate > #enddate
Am I on the right track to expand this out to include each month in one query or would I be better off taking what I have, and creating a stored procedure to run this query for each month and union the results together?

How to get new clients by months in SQL Server

I have a table Clients.
Every client has da_reg (date registered in our system). I need to make a report:
By months - total number of clients (count(distinct customernumber)); and new customers by da_reg date (I can do this per month like insert all clients from past month into temp table and then compare WHERE da_reg < 'date' and customerid not in (select customerid from #temp) - however it takes a lot of time to every time compare).
How to make it easiest way? In 1-2 steps?
Please help!
Thanks in advance!
please try this
select count(*) as new_count,
month(da_reg) as month,year(da_reg) as year
(select count(*) from tbl a where tbl.da_reg>=a.da_reg) as total_cus
from tbl
group by month(da_reg),year(da_reg)
You can Select DAtE_TIME column by month and then calc an number of row :Example for August
SELECT *,count(a.id)
FROM TABLE A as a
WHERE DATEPART(month, MY_DATETIME) = 8
where a.id PK of A

Resources