Multiple data sets in stored procedure in SSRS - sql

I have a SP that returns four different result sets, but for it to be used in SSRS report i need to have it configured in a proper way.
USE LearnShare
GO
IF OBJECT_ID (N'dbo.JH_LearnShare_ActiveUsers', N'P') IS NOT NULL
DROP PROCEDURE dbo.JH_LearnShare_ActiveUsers
GO
CREATE PROCEDURE dbo.JH_LearnShare_ActiveUsers
#enddate as date
AS
Begin
--Declare #enddate as date
--set #enddate = '6/30/2014'
Select COUNT (distinct p.PersonID) as [Total Active Users] --50621
FROM Enrollment E inner join
Person p on p.PersonID = e.[Person ID]
WHERE p.active = 1
and FirstLaunch between DATEADD(m,-11,DATEADD(mm, DATEDIFF(m,0,#enddate), 0)) AND #enddate
--DATEADD(m,-11,DATEADD(mm, DATEDIFF(m,0,GETDATE()), 0)) AND GETDATE()
and [Completion Date] between DATEADD(m,-11,DATEADD(mm, DATEDIFF(m,0,#enddate), 0)) AND #enddate
--and convert(varchar(10),[Enrollment Date] , 120) < convert(varchar(10),FirstLaunch , 120) --118669
--and FirstLaunch <> '1900-01-01 00:00:00.000' -- this doesn't matter when adding [completion date] in where clause
Select COUNT (distinct p.PersonID) as [Total Active Online Users] --49269
FROM Enrollment E inner join
Person p on p.PersonID = e.[Person ID]
left join class c
on e.[resource id] = c.[resource id]
WHERE p.active = 1
and FirstLaunch between DATEADD(m,-11,DATEADD(mm, DATEDIFF(m,0,#enddate), 0)) AND #enddate
--DATEADD(m,-11,DATEADD(mm, DATEDIFF(m,0,GETDATE()), 0)) AND GETDATE()
and [Completion Date] between DATEADD(m,-11,DATEADD(mm, DATEDIFF(m,0,#enddate), 0)) AND #enddate
and c.[Resource ID] is null
select COUNT (distinct p.personID) as [User with ILT courses] --22656
from Person p
inner join Enrollment e on p.PersonID = e.[Person ID]
inner join Resources r on e.[Resource ID] = r.[Resource ID]
inner join Class c on r.[Resource ID] = c.[Resource ID]
where p.Active = 1
and c.[Class Date] between DATEADD(m,-11,DATEADD(mm, DATEDIFF(m,0,#enddate), 0)) AND #enddate
and e.FirstLaunch between DATEADD(m,-11,DATEADD(mm, DATEDIFF(m,0,#enddate), 0)) AND #enddate
--DATEADD(m,-11,DATEADD(mm, DATEDIFF(m,0,GETDATE()), 0)) AND GETDATE()
and e.[Completion Date] between DATEADD(m,-11,DATEADD(mm, DATEDIFF(m,0,#enddate), 0)) AND #enddate
SELECT DateName(yyyy, FirstLaunch) EnrollmentYear, DATENAME(month, FirstLaunch) AS EnrollmentMonth , Count(distinct p.PersonID) as ActiveUsers --190312
FROM Enrollment E inner join
Person p on p.PersonID = e.[Person ID]
WHERE p.active = 1
and FirstLaunch between DATEADD(m,-11,DATEADD(mm, DATEDIFF(m,0,#enddate), 0)) AND #enddate
and [Completion Date] between DATEADD(m,-11,DATEADD(mm, DATEDIFF(m,0,#enddate), 0)) AND #enddate
--and convert(varchar(10),[Enrollment Date] , 120) < convert(varchar(10),FirstLaunch , 120) --118669
--and FirstLaunch <> '1900-01-01 00:00:00.000' -- this doesn't matter when adding [completion date] in where clause
AND [Completion Date] <> '1900-01-01 00:00:00.000'
GROUP BY DateName(yyyy,FirstLaunch) , DATENAME(month,FirstLaunch), DATEPART(MONTH,FirstLaunch)
ORDER BY DateName(yyyy,FirstLaunch) desc , DATEPART(MONTH,FirstLaunch) DESC
End
I tried following
Create StoredProcedure sp_MultipleDataSets(#Param nvarchar(10))
as
begin
if(#Param == "first")
begin
SELECT EMPID, ENAME, JOB, SAL, DEPTID FROM EMP -- first result set
end
if(#Param == "second")
begin
SELECT DEPTID, DNAME, LOC FROM DEPT --second result set
end
end
Example adding if (#enddate == "first") begin select..... end but its giving me an error
Msg 102, Level 15, State 1, Procedure JH_LearnShare_ActiveUsers, Line 15
Incorrect syntax near '='.
any help, please. Thanks!

I know this is late but maybe this response will help someone finding this later on.
You could write the SP in that way, however it seems unnecessarily complicated. There should be no reason you can't just write 4 different stored procedures. However, if you want to go down that route, that will work. EX:
IF #datasets = 1
begin
select 1
end
IF #datasets = 2
begin
select 2
end

Related

SQL- Grouping and counting # of days w/o overlapping days

I am trying to group a total count of days within a month that a patient had a catheter line inserted. The data is broken down into stints so is not contiguous throughout the month. I also do not to count overlapping days between the stints. See screenshot and query below.
DECLARE #start_date DATETIME
DECLARE #end_date DATETIME
SET #start_date = '2/1/2022'
SET #end_date = '2/28/2022';
CREATE TABLE mytable(
Patient_ID INTEGER NOT NULL PRIMARY KEY
,startdate DATE NOT NULL
,enddate DATE NOT NULL
,Type_of_Line VARCHAR(4) NOT NULL
,Insertion_Date DATE NOT NULL
,Removal_Date DATE
,_of_Cath_Days INTEGER NOT NULL
);
INSERT INTO mytable(Patient_ID,startdate,enddate,Type_of_Line,Insertion_Date,Removal_Date,_of_Cath_Days) VALUES (10247,'2022-01-16','2022-02-11','Port','2021-08-03 00:00:00.000',NULL,11);
INSERT INTO mytable(Patient_ID,startdate,enddate,Type_of_Line,Insertion_Date,Removal_Date,_of_Cath_Days) VALUES (10247,'2022-02-11','2022-02-15','Port','2021-08-03 00:00:00.000',NULL,5);
INSERT INTO mytable(Patient_ID,startdate,enddate,Type_of_Line,Insertion_Date,Removal_Date,_of_Cath_Days) VALUES (10247,'2022-02-15','2022-02-24','Port','2021-08-03 00:00:00.000',NULL,10);
INSERT INTO mytable(Patient_ID,startdate,enddate,Type_of_Line,Insertion_Date,Removal_Date,_of_Cath_Days) VALUES (10247,'2022-02-24','2022-03-23','Port','2021-08-03 00:00:00.000',NULL,5);
WITH stat
AS (SELECT pt.ptkey,
ptid,
ptptinfusionstatus.startdate,
ptptinfusionstatus.enddate
FROM pt
LEFT JOIN ptptinfusionstatus
ON ptptinfusionstatus.ptkey = pt.ptkey
LEFT JOIN ptinfusionstatus
ON ptinfusionstatus.ptinfusionstatuskey =
ptptinfusionstatus.ptinfusionstatuskey
WHERE ptptinfusionstatus.ptinfusionstatuskey IN ( 1, 5 )),
access1
AS (SELECT d.NAME,
d.pharmacyeventandoutcometypedetailkey,
T.pharmacyeventandoutcometypekey
FROM pharmacyeventandoutcometypedetail d WITH (nolock)
LEFT JOIN pharmacyeventandoutcometype t WITH (nolock)
ON t.pharmacyeventandoutcometypekey =
d.pharmacyeventandoutcometypekey
LEFT JOIN pharmacyeventandoutcomelist l WITH (nolock)
ON l.pharmacyeventandoutcomelistkey =
t.pharmacyeventandoutcomelistkey
WHERE l.pharmacyeventandoutcomelistkey = 2),
access2
AS (SELECT stat.ptkey,
stat.ptid,
stat.startdate,
stat.enddate,
Isnull(devicetype.NAME, '') [Access Device_Type],
ppad.insertiondate [Access Device_Insertion Date],
ppad.removaldate [Access Device_Removal Date]
FROM stat WITH (nolock)
JOIN pharmacyptaccessdevice ppad WITH(nolock)
ON ppad.ptkey = stat.ptkey
LEFT JOIN access1 devicetype WITH (nolock)
ON devicetype.pharmacyeventandoutcometypedetailkey =
ppad.accessdevicetypekey
AND devicetype.pharmacyeventandoutcometypekey = 4)
--***MAIN QUERY***
SELECT access2.[ptid] AS 'Patient ID',
access2.startdate,
access2.enddate,
access2.[access device_type] AS 'Type of Line',
access2.[access device_insertion date] AS 'Insertion Date',
access2.[access device_removal date] AS 'Removal Date',
Datediff(d, CASE WHEN [access device_insertion date] >= #start_date AND
[access device_insertion date] >=access2.startdate THEN
access2.[access device_insertion date] WHEN access2.startdate >=
access2.[access device_insertion date] AND
access2.startdate >= #start_date THEN access2.startdate ELSE #start_date
END,
CASE WHEN #end_date <= Isnull(access2.enddate, #end_date) AND #end_date
<= Isnull(access2.[access device_removal date], #end_date) THEN #end_date
WHEN access2.enddate IS NOT NULL AND access2.enddate < #end_date AND
access2.enddate <= Isnull(access2.[access device_removal date],
access2.enddate) THEN access2.enddate ELSE
access2.[access device_removal date] END) + 1 AS '# of Cath Days'
FROM access2
WHERE access2.startdate <= #end_date
AND ( access2.enddate >= #start_date
OR access2.enddate IS NULL )
AND access2.[access device_insertion date] <= #end_date
AND ( access2.[access device_removal date] >= #start_date
OR access2.[access device_removal date] IS NULL )
AND access2.ptid = '10247'
I tried grouping by patient and adding a sum of days at the patient group level in SQL Reporting Services, but could not get around the overlapping days so the counts are all wrong.
Based on the data provided, below is an example code that will group based on patientId and if start date equals end date then it will subtract 1 from number of days.
DECLARE #start_date DATETIME
DECLARE #end_date DATETIME
SET #start_date = '2/1/2022'
SET #end_date = '2/28/2022';
declare #mytable table(
Patient_ID INTEGER NOT NULL -- PRIMARY KEY
,startdate DATE NOT NULL
,enddate DATE NOT NULL
,Type_of_Line VARCHAR(4) NOT NULL
,Insertion_Date DATE NOT NULL
,Removal_Date DATE
,_of_Cath_Days INTEGER NOT NULL
);
INSERT INTO #mytable(Patient_ID,startdate,enddate,Type_of_Line,Insertion_Date,Removal_Date,_of_Cath_Days) VALUES (10247,'2022-01-16','2022-02-11','Port','2021-08-03 00:00:00.000',NULL,11);
INSERT INTO #mytable(Patient_ID,startdate,enddate,Type_of_Line,Insertion_Date,Removal_Date,_of_Cath_Days) VALUES (10247,'2022-02-11','2022-02-15','Port','2021-08-03 00:00:00.000',NULL,5);
INSERT INTO #mytable(Patient_ID,startdate,enddate,Type_of_Line,Insertion_Date,Removal_Date,_of_Cath_Days) VALUES (10247,'2022-02-15','2022-02-24','Port','2021-08-03 00:00:00.000',NULL,10);
INSERT INTO #mytable(Patient_ID,startdate,enddate,Type_of_Line,Insertion_Date,Removal_Date,_of_Cath_Days) VALUES (10247,'2022-02-24','2022-03-23','Port','2021-08-03 00:00:00.000',NULL,5);
select
Patient_ID
, startdate
, enddate
, Type_of_Line
, Insertion_Date
, Removal_Date
, LAG([enddate]) OVER (ORDER BY [startdate]) as compareenddate
from #mytable
select Patient_ID
, min(startdate) as startdate
, max(enddate) as enddate
, max(Type_of_Line) as Type_of_Line
, min(Insertion_Date) as Insertion_Date
, max(Removal_Date) as Removal_Date
, sum(iif(startdate = isnull(compareenddate, '1900-01-01'), _of_Cath_Days - 1, _of_Cath_Days) )
from
(
select
Patient_ID
, startdate
, enddate
, Type_of_Line
, Insertion_Date
, Removal_Date
, _of_Cath_Days
, LAG([enddate]) OVER (ORDER BY [startdate]) as compareenddate
from #mytable
) x
group by Patient_ID
Query result

Data Table with Current Week and Those Dates One Year Ago

I'm trying to create one sql table with the current week's data (always changing) as well as those dates data from the previous year. I have multiple tables that I have to join but am not sure how to create it all into one table. Here is what I have so far:
------- CURRENT YEAR -------
DECLARE
#CURRENTDATE DATE,
#BEGINDATE DATE
SET #CURRENTDATE = CONVERT(DATE,GETDATE()) ---// TODAY'S DATE //---
SET #BEGINDATE = DATEADD(DAY, -7, GETDATE()) ---// A WEEK BEFORE TODAY'S DATE //---
SELECT SALES.*, RECRUITS.Recruits
FROM
(
SELECT
CONVERT(VARCHAR(10), A.[ORDER DATE], 101) AS 'DAY'
, 'Sales Revenue Current Year' = FORMAT(SUM(A.[GRAND TOTAL]) ,'C', 'EN-US')
, 'Comm. Sales Volume Current Year' = FORMAT(sum(a. [QUALIFYING VOLUME]), 'C', 'EN-US')
FROM TABLE1 a
WHERE CONVERT(VARCHAR(10), A.[ORDER DATE], 101) >= #BEGINDATE AND CONVERT(VARCHAR(10), A.[ORDER DATE], 101) < #CURRENTDATE
GROUP BY CONVERT(VARCHAR(10), A.[ORDER DATE], 101)
) SALES,
(
SELECT
CONVERT(VARCHAR(10),a.[start date],101) AS 'DAY'
,count(b.[id number]) as Recruits
from TABLE2 a
left join
TABLE3 b
on a.enroller = b. [id number]
WHERE CONVERT(VARCHAR(10), A.[START DATE], 101) >= #BEGINDATE AND CONVERT(VARCHAR(10), A.[START DATE], 101) < #CURRENTDATE
group by a.[start date]
) RECRUITS
WHERE SALES.DAY = RECRUITS.DAY
I have the same script for the previous year. It is the same except I set the dates to -366 and -373 days. Any help would be great!
You can use multiple dates with an "OR", like below, but a better solution would be to use a date dimensional table, a list of every daily date with things like "WeekOfYear", "WeekOfMonth", "QuarterOfYear", "IsHoliday", etc. Then you can join your date against that table and query "where t1.WeekOfYear = t2.WeekOfYear".
DECLARE
#EndDate DATE = GETDATE() ---// TODAY'S DATE //---
, #StartDate DATE = DATEADD(DAY, -7, GETDATE()) ---// A WEEK BEFORE TODAY'S DATE //---
, #LYStartDate DATE = DATEADD(YEAR, -1, GETDATE()) ---// A YEAR BEFORE TODAY'S DATE //---
, #LYEndDate DATE = DATEADD(DAY, -7, DATEADD(YEAR, -1, GETDATE())) ---// A YEAR AND A WEEK BEFORE TODAY'S DATE //---
SELECT SALES.*, RECRUITS.Recruits
FROM
(
SELECT
'DAY' = CONVERT(VARCHAR(10), A.[ORDER DATE], 101)
, 'Sales Revenue Current Year' = FORMAT(SUM(A.[GRAND TOTAL]) ,'C', 'EN-US')
, 'Comm. Sales Volume Current Year' = FORMAT(sum(a. [QUALIFYING VOLUME]), 'C', 'EN-US')
FROM TABLE1 a
WHERE (
(CAST(A.[ORDER DATE] AS DATE) >= #StartDate AND CAST(A.[ORDER DATE] AS DATE) <= #EndDate)
OR
(CAST(A.[ORDER DATE] AS DATE) >= #LYStartDate AND CAST(A.[ORDER DATE] AS DATE) <= #lyEndDate)
)
GROUP BY CAST(A.[ORDER DATE] AS DATE)
) SALES,
(
SELECT
'DAY' = CAST(a.[start date] AS DATE)
, Recruits = COUNT(b.[id number])
FROM TABLE2 a
LEFT JOIN TABLE3 b
ON a.enroller = b. [id number]
WHERE (
(CAST(A.[START DATE] AS DATE) >= #StartDate AND CAST(A.[ORDER DATE] AS DATE) <= #EndDate)
OR
(CAST(A.[START DATE] AS DATE) >= #lyStartDate AND CAST(A.[ORDER DATE] AS DATE) <= #LYEndDate)
GROUP BY CAST(a.[start date] AS DATE)
) RECRUITS
WHERE SALES.DAY = RECRUITS.DAY

Error message running query - Column name or number of supplied values does not match table definition

I am attempting to update a stored procedure and have added u.DIVISION in the code however I am not getting the error message
Column name or number of supplied values does not match table definition.
Any suggestions on what I might be missing?
SET ansi_nulls ON
go
SET quoted_identifier ON
go
ALTER PROCEDURE [dbo].[Slx_activity]
AS
DECLARE #ReportStartDate DATETIME,
#ReportEndDate DATETIME
DECLARE #Today DATETIME
SET #Today = Getdate()
DECLARE #Diff INT
SET #Diff = Datediff(day, Dateadd(day, 5, 0), #Today)
SET #ReportEndDate = Dateadd(day, #Diff - #Diff % 7, Dateadd(day, 5, 0))
SET #ReportStartDate = Datediff(day, 6, #ReportEndDate)
IF Object_id('SLXActivity', 'U') IS NOT NULL
DROP TABLE slxactivity;
SELECT ' Current Activity:' + ' ' + p.[text] AS [TYPE],
h.createdate,
p.[text],
h.[description],
h.startdate,
Cast (NULL AS DATETIME) AS COMPLETEDDATE,
NULL AS BIDNUMBER,
NULL AS BIDSTATUS,
h.userid,
h.accountid,
h.contactid,
h.opportunityid
INTO slxactivity
FROM [SalesLogix_Production].[sysdba].[activity] h
LEFT JOIN [SalesLogix_Production].[sysdba].[picklist] p
ON h.[type] = p.id
WHERE p.[text] NOT IN ( 'Personal Activity' )
AND Cast(h.startdate AS DATE) BETWEEN
#ReportStartDate AND #ReportEndDate
INSERT INTO slxactivity
SELECT ' Completed Activity:' + ' ' + p.[text] AS [TYPE],
h.createdate,
p.[text],
h.[description],
h.startdate,
h.completeddate,
NULL AS BIDNUMBER,
NULL AS BIDSTATUS,
h.userid,
h.accountid,
h.contactid,
h.opportunityid
FROM (SELECT accountid,
[description],
Min(historyid) AS HISTORYID,
completeddate
FROM [SalesLogix_Production].[sysdba].[history]
GROUP BY accountid,
[description],
completeddate) a1
LEFT JOIN [SalesLogix_Production].[sysdba].[history] h
ON a1.accountid = h.accountid
AND a1.historyid = h.historyid
LEFT JOIN [SalesLogix_Production].[sysdba].[picklist] p
ON h.[type] = p.id
WHERE p.[text] NOT IN ( 'Personal Activity' )
AND Cast(h.completeddate AS DATE) BETWEEN
#ReportStartDate AND #ReportEndDate
INSERT INTO slxactivity
SELECT 'Opportunity Added' AS [TYPE],
o.createdate,
o.status AS [TEXT],
NULL AS [DESCRIPTION],
o.estimatedclose AS STARTDATE,
NULL AS COMPLETEDDATE,
NULL AS BIDNUMBER,
NULL AS BIDSTATUS,
o.createuser,
o.accountid,
NULL AS CONTACTID,
o.opportunityid
FROM [SalesLogix_Production].[sysdba].[opportunity] o
WHERE Cast(o.createdate AS DATE) BETWEEN
#ReportStartDate AND #ReportEndDate
INSERT INTO slxactivity
SELECT 'Contact Added' AS [TYPE],
c.createdate,
NULL AS [TEXT],
NULL AS [DESCRIPTION],
NULL AS STARTDATE,
NULL AS COMPLETEDDATE,
NULL AS BIDNUMBER_STATIC,
NULL AS BID_STATUS,
c.createuser,
c.accountid,
c.contactid,
u.division,
NULL AS OPPORTUNITYID
FROM [SalesLogix_Production].[sysdba].[contact] c
LEFT JOIN [SalesLogix_Production].[sysdba].[userinfo] u
ON c.createuser = u.userid
LEFT JOIN [SalesLogix_Production].[sysdba].[usersecurity] us
ON u.userid = us.userid
WHERE Cast(c.createdate AS DATE) BETWEEN
#ReportStartDate AND #ReportEndDate
INSERT INTO slxactivity
SELECT 'Account Created' AS [TYPE],
a.createdate,
a.type AS [TEXT],
a.industry AS [DESCRIPTION],
NULL AS STARTDATE,
NULL AS COMPLETEDDATE,
NULL AS BIDNUMBER_STATIC,
NULL AS BID_STATUS,
a.createuser,
a.accountid,
NULL AS CONTACTID,
NULL AS OPPORTUNITYID
FROM [SalesLogix_Production].[sysdba].[account] a
WHERE Cast(a.createdate AS DATE) BETWEEN
#ReportStartDate AND #ReportEndDate
SELECT t.[type],
t.createdate,
t.[text],
u.username,
a.account,
c.lastname + ', ' + c.firstname AS [CONTACT],
o.[description] AS OPPORTUNITY,
oe.bidnumber_static,
oe.bid_status,
t.[description],
t.startdate,
t.completeddate,
u.division,
#ReportStartDate AS ReportStartDate,
#ReportEndDate AS ReportEndDate
FROM [SalesLogix_Production].[sysdba].[userinfo] u
JOIN [SalesLogix_Production].[sysdba].[usersecurity] us
ON u.userid = us.userid
LEFT JOIN slxactivity t
ON u.userid = t.userid
LEFT JOIN [SalesLogix_Production].[sysdba].[account] a
ON t.accountid = a.accountid
LEFT JOIN [SalesLogix_Production].[sysdba].[contact] c
ON t.contactid = c.contactid
LEFT JOIN [SalesLogix_Production].[sysdba].[opportunity] o
ON t.opportunityid = o.opportunityid
LEFT JOIN [SalesLogix_Production].[sysdba].[c_opportunity_ext] oe
ON t.opportunityid = oe.opportunityid
WHERE us.[type] NOT IN ( 'R', 'W' )
AND u.username <> 'svc_slxadmin'
You need to specify the column in the first statement which creates the table:
SELECT ' Current Activity:' + ' ' + p.[text] AS [TYPE],
h.createdate,
p.[text],
h.[description],
h.startdate,
Cast (NULL AS DATETIME) AS COMPLETEDDATE,
NULL AS BIDNUMBER,
NULL AS BIDSTATUS,
h.userid,
h.accountid,
h.contactid,
CAST(NULL AS VARCHAR(100)) AS division,
/*
you need to specify/select the column here, with the relevant
type, in this context. I assumed it's a string just for the example.
*/
h.opportunityid
INTO slxactivity
FROM [SalesLogix_Production].[sysdba].[activity] h
LEFT JOIN [SalesLogix_Production].[sysdba].[picklist] p
ON h.[type] = p.id
WHERE p.[text] NOT IN ( 'Personal Activity' )
AND Cast(h.startdate AS DATE) BETWEEN
#ReportStartDate AND #ReportEndDate

running total for each employee

I have the following query which works great to return a running total of carpool reimbursements for an individual staff member. (employee earns $30 for each 20 trips, trips roll over until the end of the year).
-- carpool quarter stats
use TRPTracking
declare #employeeID NVarChar(100), #year Char(4)
Set #employeeID = 'PSmith'
Set #year = '2014'
------
declare #startDate DateTime, #endDate DateTime
Set #startDate = '1/1/' + #year
Set #endDate = DateAdd(d,-1,DateAdd(yyyy,1,#startDate))
DECLARE #calendar TABLE (Date datetime)
WHILE (#startDate <= #endDate) BEGIN
INSERT INTO #Calendar VALUES (#startDate)
SET #startDate = DATEADD(quarter, 1, #startDate)
END
DECLARE #CarpoolTbl TABLE (quarter varchar(250), value decimal(18,1), runningTotal decimal(18,1), earned money)
DECLARE #runningTotal decimal(18,1), #earned money
SET #runningTotal = 0
SET #earned = 0
INSERT INTO #CarpoolTbl
SELECT CASE DatePart(q, c.date)
WHEN 1 THEN 'Jan-Mar'
WHEN 2 THEN 'Apr-Jun'
WHEN 3 THEN 'Jul-Sep'
WHEN 4 THEN 'Oct-Dec' END AS quarter,
IsNULL(Sum(t.value),0) AS value,
null,
0
FROM #calendar c
LEFT OUTER JOIN events e ON (DatePart(q, c.date) = DatePart(q, e.eventDate) AND e.employeeID = #employeeID AND e.eventType = 'CP' AND Year(eventDate) = #year)
LEFT JOIN types t ON t.typeID = e.eventType
GROUP BY DatePart(q, c.date)
UPDATE #CarpoolTbl
SET #earned = earned = Floor((#runningTotal + value)/20) - Floor(#runningTotal/20),
#runningTotal = runningTotal = #runningTotal + value
FROM #CarpoolTbl
SELECT quarter, value, runningTotal, earned * 30 AS earned
FROM #CarpoolTbl
Now, I want a query that returns this information for all employees. I remove the portion that relates to employeeID and I get what looks to be good. But... what is happening is my running total is running for everyone. I need it to restart for each employee. I can't quite figure out where to add the employeeID grouping in the running total.
-- carpool quarter stats
use TRPTracking
declare #year Char(4)
Set #year = '2014'
------
declare #startDate DateTime, #endDate DateTime
Set #startDate = '1/1/' + #year
Set #endDate = DateAdd(d,-1,DateAdd(yyyy,1,#startDate))
DECLARE #calendar TABLE (Date datetime)
WHILE (#startDate <= #endDate) BEGIN
INSERT INTO #Calendar VALUES (#startDate)
SET #startDate = DATEADD(quarter, 1, #startDate)
END
DECLARE #CarpoolTbl TABLE (dateQ int, quarter varchar(250), employeeID varchar(255), value decimal(18,1), runningTotal decimal(18,1), earned money)
DECLARE #runningTotal decimal(18,1), #earned money
SET #runningTotal = 0
SET #earned = 0
INSERT INTO #CarpoolTbl
SELECT
DatePart(q, c.date),
CASE DatePart(q, c.date)
WHEN 1 THEN 'Jan-Mar'
WHEN 2 THEN 'Apr-Jun'
WHEN 3 THEN 'Jul-Sep'
WHEN 4 THEN 'Oct-Dec' END AS quarter,
e.employeeID,
IsNULL(Sum(t.value),0) AS value,
null,
0
FROM #calendar c
LEFT OUTER JOIN events e ON (DatePart(q, c.date) = DatePart(q, e.eventDate)
AND e.eventType = 'CP' AND Year(eventDate) = #year)
LEFT JOIN types t ON t.typeID = e.eventType
GROUP BY e.employeeID, DatePart(q, c.date)
UPDATE #CarpoolTbl
SET #earned = earned = Floor((#runningTotal + value)/20) - Floor(#runningTotal/20),
#runningTotal = runningTotal = #runningTotal + value
FROM #CarpoolTbl
SELECT c.quarter, c.employeeID, a.DisplayName AS employee, c.value AS trips, earned * 30 AS earned
FROM #CarpoolTbl c
LEFT JOIN SBAIntranet.dbo.NTAuth a ON 'SBA\' + c.employeeID = a.AccountName
ORDER BY dateQ, employeeID
Any thoughts?
EDIT:
Unexpected result with running total for all employees, not by employee:
Qtr Employee trips tripsRunningTotal
Jan-Mar Cathy 5.0 5.0
Apr-Jun Cathy 3.0 375.5
Jul-Sep Cathy 4.0 757.0
Jan-Mar Carol 3.5 8.5
Apr-Jun Carol 16.0 391.5
Jul-Sep Carol 44.5 801.5
EDIT 2:
Ok, here is my revised, cleaner, accurate version. Now, to figure out the earned dollars portion.
-- carpool quarter stats
use TRPTracking
declare #employeeID NVarChar(100), #year Char(4)
Set #year = '2014'
------
declare #startDate DateTime, #endDate DateTime
Set #startDate = '1/1/' + #year
Set #endDate = DateAdd(d,-1,DateAdd(yyyy,1,#startDate))
;WITH cte
AS (SELECT Datepart(qq, e.eventDate) AS quarterNum,
CASE DatePart(qq, e.eventDate)
WHEN 1 THEN 'Jan-Mar'
WHEN 2 THEN 'Apr-Jun'
WHEN 3 THEN 'Jul-Sep'
WHEN 4 THEN 'Oct-Dec' END AS quarter,
e.employeeID,
Sum(t.value) AS trips
FROM events e
LEFT JOIN types t ON t.typeID = e.eventType
WHERE e.eventType = 'CP' AND Year(eventDate) = #year
GROUP BY Datepart(quarter, eventDate), e.employeeID)
SELECT a.quarter, a.employeeID, nta.DisplayName AS employee, trips,
(SELECT Sum(trips)
FROM cte b
WHERE a.employeeID = b.employeeID
AND a.quarter >= b.quarter) as runningTotal
FROM cte a
LEFT JOIN SBAIntranet.dbo.NTAuth nta ON 'SBA\' + a.employeeID = nta.AccountName
ORDER BY a.employeeID, a.quarterNum
Use Correlated Subquery to find the running total after grouping by quarter. Inner Join is another option to do this
;WITH cte
AS (SELECT Datepart(qq, dates) qq,
employee,
Sum(trips) trips
FROM Yourtable
GROUP BY Datepart(qq, dates),
employee)
SELECT Employee,
CASE qq
WHEN 1 THEN 'Jan-Mar'
WHEN 2 THEN 'Apr-Jun'
WHEN 3 THEN 'Jul-Sep'
WHEN 4 THEN 'Oct-Dec'
END AS quarter,
Trips,
(SELECT Sum(trips)
FROM cte b
WHERE a.Employee = b.Employee
AND a.qq >= b.qq) Running_Total
FROM cte a
SQLFIDDLE DEMO

Searching Week-wise/Month-wise record counts(number) and the StartDate+EndDate(datetime) of the Week/Month with Search between two Dates

I have a question in connection to this question earlier posted by me:-
Daily/Weekly/Monthly Record Count Search via StoredProcedure
I want to have the Count of Calls on Weekly-basis and Monthly-basis, Daily-basis issue is resolved.
ISSUE NUMBER #1:Weekly-basis Count of Calls and Start-Date and End-Date of Week
I have searched the Start-Date and End-Date of Week including their individual Count of Calls as well in the below-mentioned query. But the problem is that I could not get the result in one single table, although I have used the Temporary Tables(#TempTable+#TempTable2). Kindly help me in this regards.
NOTE:Table Creation commented as for executing more than once.
--CREATE TABLE #TempTable(StartDate datetime,EndDate datetime,CallCount numeric(18,5))
--CREATE TABLE #TempTable2(StartDate datetime,EndDate datetime,CallCount numeric(18,5))
DECLARE #StartDate datetime,#EndDate datetime,#StartDateTemp1 datetime,#StartDateTemp2 datetime,#EndDateTemp datetime,#Period varchar(50);
SET #StartDate='1/1/2010'; SET #EndDate='2/28/2010';
SET #StartDateTemp1=#StartDate; SET #StartDateTemp2=DATEADD(dd, 7, #StartDate );
SET #Period='Weekly';
IF (#Period = 'Weekly')
BEGIN
WHILE ((#StartDate <= #StartDateTemp1) AND (#StartDateTemp2 <= #EndDate))
BEGIN
IF((#StartDateTemp1 < #StartDateTemp2 ) AND (#StartDateTemp1 != #StartDateTemp2) )
BEGIN
SELECT
convert(varchar, #StartDateTemp1, 106) AS 'Start Date',
convert(varchar, #StartDateTemp2, 106) AS 'End Date',
COUNT(*) AS 'Call Count'
FROM TRN_Call
WHERE (CallTime >= #StartDateTemp1 AND CallTime <= #StartDateTemp2 );
END
SET #StartDateTemp1 = DATEADD(dd, 7, #StartDateTemp1);
SET #StartDateTemp2 = DATEADD(dd, 7, #StartDateTemp2);
END
END
ISSUE NUMBER #2:Monthly-basis Count of Calls and Start-Date and End-Date of Week
In this case, I have the same search, but will have to search the Call Counts plus the Start-Date and End-Date of the Month. Kindly help me in this regards as well.
DECLARE #StartDate datetime,#EndDate datetime,#StartDateTemp1 datetime,#StartDateTemp2 datetime,#EndDateTemp datetime,#Period varchar(50);
SET #StartDate='1/1/2010'; SET #EndDate='4/1/2010'; SET #StartDateTemp1=#StartDate;
--SET #StartDateTemp2=#StartDate;
SET #StartDateTemp2=DATEADD(mm, 1, #StartDate );
SET #Period='Monthly';
IF (#Period = 'Monthly')
BEGIN
WHILE ((#StartDate <= #StartDateTemp1) AND (#StartDateTemp2 <= #EndDate))
BEGIN
IF((#StartDateTemp1 < #StartDateTemp2 ) AND (#StartDateTemp1 != #StartDateTemp2) )
BEGIN
SELECT
convert(varchar, #StartDateTemp1, 106) AS 'Start Date',
convert(varchar, #StartDateTemp2, 106) AS 'End Date',
COUNT(*) AS 'Call Count'
FROM TRN_Call
WHERE (CallTime >= #StartDateTemp1 AND CallTime <= #StartDateTemp2 );
END
SET #StartDateTemp1 = DATEADD(mm, 1, #StartDateTemp1);
SET #StartDateTemp2 = DATEADD(mm, 1, #StartDateTemp2);
END
END
I believe following three simple queries suffice for what you need.
Daily
SELECT [Day] = CAST(CAST(CallTime AS INTEGER) AS DATETIME)
, [Call Count] = COUNT(*)
FROM TRN_Call
WHERE CallTime BETWEEN #StartDate AND #EndDate
GROUP BY CAST(CAST(CallTime AS INTEGER) AS DATETIME)
Weekly
SELECT [Week] = DATEPART(ww, CallTime)
, [Year] = DATEPART(yy, CallTime)
, [Call Count] = COUNT(*)
FROM TRN_Call
WHERE CallTime BETWEEN #StartDate AND #EndDate
GROUP BY DATEPART(ww, CallTime), DATEPART(yy, CallTime)
Monthly
SELECT [Month] = DATEPART(mm, CallTime)
, [Year] = DATEPART(yy, CallTime)
, [Call Count] = COUNT(*)
FROM TRN_Call
WHERE CallTime BETWEEN #StartDate AND #EndDate
GROUP BY DATEPART(mm, CallTime), DATEPART(yy, CallTime)
Simple query for find record month wise.....
SELECT invoice_no, created_at,month(created_at) month_no ,count(invoice_no) sale_count FROM sales_invoice WHERE company_id = ' .10 . ' AND status = "Approved" and year(created_at) = year(curdate()) group by month(created_at)enter code here