Related
I have a subquery that is taking multiple minutes to execute. If I pull out just the initial rows that are being added up, it only takes half a second with 2,400ish rows so I don't understand why the main query doing the sum is taking so long.
What I'm trying to do is for all the transactions in a date range, for all the workers assigned to those transactions, add up the scheduled hours for each worker.
The query is returning the correct data, it's just taking FOREVER to do it.
QUERY
SELECT scheduled_hours = COALESCE(sum(hours), 0), worker_sysid
FROM (
SELECT DISTINCT
B.DateR1,
B.DateR2,
hours = ABS((B.DAteR1 - B.DateR2) / 3600),
B.worker_sysid
FROM Trans A
OUTER APPLY (
SELECT
DateR1 = MIN(TRANS_START),
DateR2 = MAX(TRANS_END),
worker_sysid
FROM Trans
JOIN trans_workers ON trans_workers.trans_sysid = Trans.SYSID
LEFT JOIN Service ON Service.SYSID = Trans.SERVICESYSID
WHERE
TRANS_START <= A.TRANS_END AND TRANS_END >= A.TRANS_START
AND TRANS_START IS NOT NULL AND TRANS_END IS NOT NULL
AND TRANS_START != '' AND TRANS_END != ''
AND Trans.CHARGEBY IN ('Hours', 'Hour')
AND (
COALESCE(Service.overnight, 0) != 1
OR
COALESCE(Service.active_overnight, 0) = 1
)
AND TRANSDATE BETWEEN 80387 AND 80400 ### These are Clarion dates
AND trans_workers.deleted_at IS NULL
GROUP BY worker_sysid
) B
) A
WHERE worker_sysid IS NOT NULL
GROUP BY worker_sysid
TABLES
Trans: SYSID (int, pk), TRANSDATE (int, clarion-formatted date), TRANS_START / TRANS_END (UNIX timestamp), SERVICESYSID (int, fk), CHARGEBY (varchar)
trans_workers: trans_sysid, worker_sysid, deleted_at
Service: SYSID (int, pk)
UPDATE
Moving the trans_workers join out of the OUTER APPLY has reduced the execution time from 1 minute down to 16 seconds, so that's an improvement.
SELECT scheduled_hours = COALESCE(sum(hours), 0), worker_sysid
FROM (
SELECT DISTINCT
B.DateR1,
B.DateR2,
hours = ABS((B.DateR1 - B.DateR2) / 3600),
worker_sysid
FROM Trans A
JOIN trans_workers ON A.SYSID = trans_workers.trans_sysid
OUTER APPLY (
SELECT
DateR1 = MIN(TRANS_START),
DateR2 = MAX(TRANS_END),
Trans.SYSID
FROM Trans
LEFT JOIN Service ON Service.SYSID = Trans.SERVICESYSID
WHERE
TRANS_START <= A.TRANS_END AND TRANS_END >= A.TRANS_START
AND TRANS_START IS NOT NULL AND TRANS_END IS NOT NULL
AND TRANS_START != '' AND TRANS_END != ''
AND Trans.CHARGEBY IN ('Hours', 'Hour')
AND COALESCE(Service.overnight, 0) != 1
AND TRANSDATE BETWEEN 80387 AND 80400
GROUP BY Trans.SYSID
) B
) A
WHERE worker_sysid IS NOT NULL
GROUP BY worker_sysid
ORDER BY worker_sysid
Thanks to https://www.sqlservercentral.com/forums/topic/consolidate-overlapping-date-periods I have a query that executes in under a second and returns what appear to be the correct hours. Only problem being I don't understand what's happening.
DECLARE #start INTEGER, #end INTEGER;
SET #start = 80401; --06/02/2021
SET #end = 80414; --19/02/2021
WITH cteTemp
AS (
SELECT
worker_sysid,
BeginDate =
CASE
WHEN ROW_NUMBER() OVER (PARTITION BY worker_sysid ORDER BY theDate) - openCnt = 0 THEN theDate
END,
EndDate =
CASE
WHEN ROW_NUMBER() OVER (PARTITION BY worker_sysid ORDER BY theDate) - closeCnt = 0 THEN theDate
END
FROM (
SELECT
worker_sysid,
theDate = DATEADD(day, 0, DATEDIFF(day, 0, (dateadd(day,[TRANSDATE]-(4),'1801-01-01')))) + DATEADD(day, 0 - DATEDIFF(day, 0, DATEADD(second, TRANS_START - DATEDIFF(S, GETDATE(), GETUTCDATE()), '1970-01-01')), DATEADD(second, TRANS_START - DATEDIFF(S, GETDATE(), GETUTCDATE()), '1970-01-01')),
closeCnt = NULL,
openCnt = (ROW_NUMBER() OVER (PARTITION BY worker_sysid ORDER BY DATEADD(day, 0, DATEDIFF(day, 0, (dateadd(day,[TRANSDATE]-(4),'1801-01-01')))) + DATEADD(day, 0 - DATEDIFF(day, 0, DATEADD(second, TRANS_START - DATEDIFF(S, GETDATE(), GETUTCDATE()), '1970-01-01')), DATEADD(second, TRANS_START - DATEDIFF(S, GETDATE(), GETUTCDATE()), '1970-01-01'))) * 2) - 1
FROM
Trans
INNER JOIN trans_workers ON trans_workers.trans_sysid = Trans.SYSID
JOIN Service ON Service.SYSID = Trans.SERVICESYSID
WHERE
worker_sysid IS NOT NULL
AND Trans.deleted_at IS NULL
AND trans_workers.deleted_at IS NULL
AND Trans.CHARGEBY IN ('Hour', 'Hours')
AND (transCancelled IS NULL OR transCancelled != 1)
AND (
COALESCE(Service.overnight, 0) = 0
)
AND TRANSDATE BETWEEN #start AND #end
UNION ALL
SELECT
worker_sysid,
theDate = DATEADD(day, 0, DATEDIFF(day, 0, (dateadd(day,[TRANSDATE]-(4),'1801-01-01')))) + DATEADD(day, 0 - DATEDIFF(day, 0, DATEADD(second, TRANS_END - DATEDIFF(S, GETDATE(), GETUTCDATE()), '1970-01-01')), DATEADD(second, TRANS_END - DATEDIFF(S, GETDATE(), GETUTCDATE()), '1970-01-01')),
closeCnt = ROW_NUMBER() OVER (PARTITION BY worker_sysid ORDER BY worker_sysid, DATEADD(day, 0, DATEDIFF(day, 0, (dateadd(day,[TRANSDATE]-(4),'1801-01-01')))) + DATEADD(day, 0 - DATEDIFF(day, 0, DATEADD(second, TRANS_END - DATEDIFF(S, GETDATE(), GETUTCDATE()), '1970-01-01')), DATEADD(second, TRANS_END - DATEDIFF(S, GETDATE(), GETUTCDATE()), '1970-01-01'))) * 2,
openCnt = NULL
FROM
Trans
JOIN trans_workers ON trans_workers.trans_sysid = Trans.SYSID
JOIN Service ON Service.SYSID = Trans.SERVICESYSID
WHERE
worker_sysid IS NOT NULL
AND Trans.deleted_at IS NULL
AND trans_workers.deleted_at IS NULL
AND Trans.CHARGEBY IN ('Hour', 'Hours')
AND (transCancelled IS NULL OR transCancelled != 1)
AND (
COALESCE(Service.overnight, 0) = 0
)
AND TRANSDATE BETWEEN #start AND #end
)
AS baseSelected
)
SELECT scheduled_hours = SUM(hours), worker_sysid
FROM (
SELECT
dt.worker_sysid,
hours = CAST(ABS(DATEDIFF(second, MIN(dt.BeginDate), MAX(dt.EndDate))) / 3600.0 AS DECIMAL(10,2))
FROM (
SELECT
worker_sysid,
BeginDate,
EndDate,
grpID =
IIF(BeginDate IS NOT NULL, ROW_NUMBER() OVER (PARTITION BY worker_sysid ORDER BY worker_sysid, BeginDate), ROW_NUMBER() OVER (PARTITION BY worker_sysid ORDER BY worker_sysid, EndDate))
FROM
cteTemp
WHERE
BeginDate IS NOT NULL OR EndDate IS NOT NULL
)
AS dt
GROUP BY dt.worker_sysid,grpID
) AS final_table
GROUP BY worker_sysid ORDER BY worker_sysid
Bonus points to myself for conversions because the DATE of each transaction is in Clarion and the TIME of each transaction is a Unix timestamp
SELECT
COUNT(*) AS Previous_Live_Members, m.HomeBranch, m.LocationName
FROM
AX.Mem M
WHERE
m.ActiveStart < DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 13, 0)
AND (m.ActiveEnd > DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 13, 0) OR M.ActiveEnd IS NULL)
GROUP BY
m.HomeBranch, m.LocationName
I already converted but results are different. Might be some issue in my query. I want to convert simple query into CTE table.
WITH CTE_A AS
(
SELECT
SUM(CASE
WHEN M.ActiveStart < DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 13, 0)
AND M.ActiveEnd > DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 13, 0) OR M.ActiveEnd IS NULL
THEN 1
ELSE 0
END) AS Previous_No_of_Live_Member,
M.HomeBranch,
M.LocationName
FROM
AX.Mem M
GROUP BY
M.HomeBranch, M.LocationName
)
SELECT
Previous_No_of_Live_Member,
HomeBranch,
LocationName
FROM
CTE_A
The CTE version is missing a pair of parenthesis.
You are using a query on ActiveEnd where (ActiveEnd > ... OR ActiveEnd IS NULL). This should be in parenthesis in the CTE version too.
Compare this line
...
and (m.ActiveEnd > DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 13, 0) or M.ActiveEnd is null)
with the CTE version
...
AND
M.ActiveEnd > DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 13, 0)
or M.ActiveEnd is null then 1 else 0 end)
I think it should be (indicated with ^ where I think parenthesis should go):
...
AND
(M.ActiveEnd > DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 13, 0)
^ or M.ActiveEnd is null) then 1 else 0 end)
^
I need some help summing two (or more) alias columns.
I know I need a derived table to do it, but so far I get lost with online tutorials and documentation as their examples are far too simple. they only have one table, two columns, etc.
What could be my best option here:
I need to calculate the sum of two alias columns: 'InFxO' and 'OnTxO' and my code is as follows:
ALTER PROC [dbo].[DIFOTIS]
#Mode as Varchar (5)
AS
Begin
Declare
#StartDate date,
#EndDate date
SET #StartDate=
CASE #Mode
WHEN 'MTD' THEN DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0)
WHEN 'YTD' THEN DATEADD(yy,DATEDIFF(yy,0,GETDATE()),0)
WHEN 'QTD' THEN DATEADD(qq,DATEDIFF(qq,0,GETDATE()),0)
WHEN 'WTD' THEN DATEADD(wk,DATEDIFF(wk,0,GETDATE()),0)
END
Set #EndDate=
CASE #Mode
WHEN 'MTD' THEN DATEADD(mm,DATEDIFF(mm,0,GETDATE())+1,0)
WHEN 'YTD' THEN DATEADD(yy,DATEDIFF(yy,0,GETDATE())+1,0)
WHEN 'QTD' THEN DATEADD(qq,DATEDIFF(qq,0,GETDATE())+1,0)
WHEN 'WTD' THEN DATEADD(wk,DATEDIFF(wk,0,GETDATE())+1,0)
END
Select DATEPART(ISO_WEEK,d.DateOpn) AS 'Week#'
,Clients.CustCateg, Clients.ClntGroup
,d.DocumentCode as 'CORD_DocumentCode'
,CDSPDocs.DocumentCode AS 'DESP_DocumentCode'
,Count(CORDLines.Qnty) AS 'Cord_Lines'
,SUM(CORDLines.Qnty) AS 'CORD_Qty'
,Count(CDSPLines.Qnty) AS 'DESP_Lines'
,Sum(CDSPLines.Qnty) AS 'DESP_Qty'
,CDSPLines.Status, d.Status as d_status
,d.OpenDate, d.DateDue
,CDSPDocs.PostDate AS 'DESP_PostedDate'
,d.DocType, DATEDIFF(day, d.OpenDate, d.DateDue) AS 'Lead times'
--in-full
,CASE WHEN SUM(CORDLines.Qnty) = Sum(CDSPLines.Qnty) THEN '1' ELSE '0' END as InFxO
--On-Time by order according to Despatch SLAs
,CASE WHEN (Clients.ClntGroup IN ('Local Market','Local Market - Pharm','Web Sales - Local','Web Sales - Export', 'Mail Order','Mail Order - Export')) AND (Datediff(day, d.OpenDate, CDSPDocs.PostDate) - (Datediff(Week, d.OpenDate, CDSPDocs.PostDate)*2) <= 2) then '1'
WHEN (Clients.ClntGroup = 'Export Market') AND (Datediff(day, d.OpenDate, CDSPDocs.PostDate) - (Datediff(Week, d.OpenDate, CDSPDocs.PostDate)*2) <= 14) then '1'
WHEN (Clients.ClntGroup = 'Export Market') or Clients.CustCateg = 'UK Transfer' AND (d.DateDue >= CDSPDocs.PostDate) then '1'
ELSE '0'
END as OnTxO
From dbo.Documents AS d INNER JOIN
dbo.Clients ON d.ObjectID = dbo.Clients.ClntID AND Clients.ClientName <> 'Samples - Free / Give-aways' LEFT Outer JOIN
dbo.DocumentsLines AS CORDLines ON d.DocID = CORDLines.DocID AND CORDLines.TrnType = 'L'
LEFT OUTER JOIN
dbo.DocumentsLines AS CDSPLines ON CORDLines.TranID = CDSPLines.SourceID AND CDSPLines.TrnType = 'L' AND (CDSPLines.Status = 'Posted' OR CDSPLines.Status = 'Closed') LEFT OUTER JOIN
dbo.Documents AS CDSPDocs ON CDSPLines.DocID = CDSPDocs.DocID
WHERE (d.DocType IN ('CASW', 'CORD','MORD'))
AND (CORDLines.LneType NOT In ('Fght','MANF','Stor', 'PACK','EXPS'))
AND d.DateOpn >= #StartDate AND d.DateOpn < #EndDate
AND (CORDLines.LneType is not null)
AND (d.DateDue <= Convert(Date, GetDate(), 101))
Group by d.DateOpn
,d.DocumentCode
,Clients.CustCateg
,CDSPDocs.DocumentCode
,d.[Status]
,d.DocType
,d.OpenDate
,d.DateReq
,CDSPDocs.PostDate
,CDSPLines.[Status]
,Clients.ClntGroup
,d.DocumentName
,d.DateDue
,d.DateOpn
ORDER BY d.DateOpn, 'Week#'
END
GO
All help is appreciated.
Thanks
H
Below is an example that wraps the original query in a derived table so that you don't need to repeat the CASE expressions for the SUM. You could similarly wrap the query in a common table expression to achieve the same result.
I suggest you use single-quotes only to enclose string literals and enclose identifiers (column names, aliases, and object names) with either square brackets or double quotes as described in the SQL Server Books Online reference (http://msdn.microsoft.com/en-us/library/ms175874.aspx). Identifiers need be enclosed only when they don't conform to identifier naming rules or are a reserved keyword.
ALTER PROC dbo.DIFOTIS #Mode AS varchar(5)
AS
BEGIN
DECLARE #StartDate date
, #EndDate date;
SET #StartDate = CASE #Mode
WHEN 'MTD'
THEN DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0)
WHEN 'YTD'
THEN DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)
WHEN 'QTD'
THEN DATEADD(qq, DATEDIFF(qq, 0, GETDATE()), 0)
WHEN 'WTD'
THEN DATEADD(wk, DATEDIFF(wk, 0, GETDATE()), 0)
END;
SET #EndDate = CASE #Mode
WHEN 'MTD'
THEN DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) + 1, 0)
WHEN 'YTD'
THEN DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, 0)
WHEN 'QTD'
THEN DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) + 1, 0)
WHEN 'WTD'
THEN DATEADD(wk, DATEDIFF(wk, 0, GETDATE()) + 1, 0)
END;
SELECT Week#
, CustCateg
, ClntGroup
, CORD_DocumentCode
, DESP_DocumentCode
, Cord_Lines
, CORD_Qty
, DESP_Lines
, DESP_Qty
, Status
, d_status
, OpenDate
, DateDue
, DESP_PostedDate
, DocType
, [Lead times]
, InFxO
, OnTxO
, InFxO + OnTxO AS InFullAndOneTime
FROM (
SELECT DATEPART(ISO_WEEK, d.DateOpn) AS Week#
, Clients.CustCateg
, Clients.ClntGroup
, d.DocumentCode AS CORD_DocumentCode
, CDSPDocs.DocumentCode AS DESP_DocumentCode
, COUNT(CORDLines.Qnty) AS Cord_Lines
, SUM(CORDLines.Qnty) AS CORD_Qty
, COUNT(CDSPLines.Qnty) AS DESP_Lines
, SUM(CDSPLines.Qnty) AS DESP_Qty
, CDSPLines.Status
, d.Status AS d_status
, d.OpenDate
, d.DateDue
, CDSPDocs.PostDate AS DESP_PostedDate
, d.DocType
, DATEDIFF(DAY, d.OpenDate, d.DateDue) AS [Lead times]
--in-full
, CASE WHEN SUM(CORDLines.Qnty) = SUM(CDSPLines.Qnty) THEN 1
ELSE 0
END AS InFxO
--On-Time by order according to Despatch SLAs
, CASE WHEN ( Clients.ClntGroup IN ( 'Local Market',
'Local Market - Pharm',
'Web Sales - Local',
'Web Sales - Export',
'Mail Order',
'Mail Order - Export' ) )
AND ( DATEDIFF(DAY, d.OpenDate, CDSPDocs.PostDate)
- ( DATEDIFF(WEEK, d.OpenDate,
CDSPDocs.PostDate) * 2 ) <= 2 )
THEN 1
WHEN ( Clients.ClntGroup = 'Export Market' )
AND ( DATEDIFF(DAY, d.OpenDate, CDSPDocs.PostDate)
- ( DATEDIFF(WEEK, d.OpenDate,
CDSPDocs.PostDate) * 2 ) <= 14 )
THEN 1
WHEN ( Clients.ClntGroup = 'Export Market' )
OR Clients.CustCateg = 'UK Transfer'
AND ( d.DateDue >= CDSPDocs.PostDate ) THEN '1'
ELSE 0
END AS OnTxO
FROM dbo.Documents AS d
INNER JOIN dbo.Clients ON d.ObjectID = dbo.Clients.ClntID
AND Clients.ClientName <> 'Samples - Free / Give-aways'
LEFT OUTER JOIN dbo.DocumentsLines AS CORDLines ON d.DocID = CORDLines.DocID
AND CORDLines.TrnType = 'L'
LEFT OUTER JOIN dbo.DocumentsLines AS CDSPLines ON CORDLines.TranID = CDSPLines.SourceID
AND CDSPLines.TrnType = 'L'
AND ( CDSPLines.Status = 'Posted'
OR CDSPLines.Status = 'Closed'
)
LEFT OUTER JOIN dbo.Documents AS CDSPDocs ON CDSPLines.DocID = CDSPDocs.DocID
WHERE ( d.DocType IN ( 'CASW', 'CORD', 'MORD' ) )
AND ( CORDLines.LneType NOT IN ( 'Fght', 'MANF', 'Stor',
'PACK', 'EXPS' ) )
AND d.DateOpn >= #StartDate
AND d.DateOpn < #EndDate
AND ( CORDLines.LneType IS NOT NULL )
AND ( d.DateDue <= CONVERT(date, GETDATE(), 101) )
GROUP BY d.DateOpn
, d.DocumentCode
, Clients.CustCateg
, CDSPDocs.DocumentCode
, d.Status
, d.DocType
, d.OpenDate
, d.DateReq
, CDSPDocs.PostDate
, CDSPLines.Status
, Clients.ClntGroup
, d.DocumentName
, d.DateDue
, d.DateOpn
) AS derived_table
ORDER BY d.DateOpn
, Week#;
END;
GO
I have a query that returns a score on whether or not 3 of the columns = 1 and then if the ProviderID exists in the 2nd table. I need to be able to return a score for each month for 6 months using column Time_Stamp, not including current month. The below returns the score for last month. How can I include the remaining 5 months and ROW_NUMBER() them?
DECLARE #ProviderID int = '1717';
WITH cte as
(
SELECT TOP 1
a.ProviderID, Time_Stamp,
SUM(CASE WHEN [AdditionalReports] = '1' THEN 5 ELSE 0 END) as AdditionalReports,
SUM(CASE WHEN [UniqueReportRequests] = '1' THEN 15 ELSE 0 END) as UniqueReportsRequests,
SUM(CASE WHEN [SurveyCompleted] = '1' THEN 30 ELSE 0 END) as SurveyCompleted,
MAX(CASE WHEN b.ProviderID IS NULL THEN 0 ELSE 50 END) as SubscriptionExists
FROM
ProviderValueCard a
LEFT JOIN
SubscriptionsTV b ON a.ProviderID = b.ProviderID
WHERE
a.ProviderID = #ProviderID AND GroupID = 2
AND Time_Stamp BETWEEN DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 1, 0) AND DATEADD(DAY, -(DAY(GETDATE())), GETDATE())
GROUP BY
Time_Stamp, a.ProviderID, event
ORDER BY
event DESC, Time_Stamp DESC
)
SELECT
ProviderID, Time_Stamp,
(AdditionalReports + UniqueReportsRequests + SurveyCompleted + SubscriptionExists) AS TotalScore
FROM
cte
Here is how to grab the first/last day of previous months:
2 months ago:
DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 2, 0) as FirstD2monthsago,
DATEADD(DAY, -DAY(GETDATE()), DATEADD(MONTH, -1, GETDATE())) AS last_day_2_months_ago
3 months ago etc:
DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 3, 0) as FirstD3monthsago,
DATEADD(DAY, -DAY(GETDATE()), DATEADD(MONTH, -2, GETDATE())) AS last_day_3_months_ago
Desired output
ProviderID Time_Stamp TotalScore Row_Number
----------- ----------------------- -----------
1717 2014-08-29 12:11:17.610 70 1
1717 2014-07-29 12:11:17.610 95 2
1717 2014-06-29 12:11:17.610 100 3
1717 2014-05-29 12:11:17.610 70 4
1717 2014-04-29 12:11:17.610 70 5
1717 6
DECLARE #ProviderID INT, #Now DATETIME, #Months INT
SELECT #ProviderID = 1717, #Now = GETDATE(), #Months = 5
WITH
date_range_cte AS (
SELECT 1 AS RowNum, DATEADD(mm,-1,#Now) AS StartDate, DATEADD(mm,0,#Now) AS EndDate
UNION ALL
SELECT d.RowNum + 1 AS RowNum, DATEADD(mm,(-d.RowNum - 1),#Now) AS StartDate, DATEADD(mm,-d.RowNum,#Now) AS EndDate
FROM date_range_cte d
WHERE d.RowNum + 1 <= #Months
),
main_cte AS (
SELECT
ROW_NUMBER() OVER (PARTITION BY a.ProviderID, d.RowNum, d.StartDate ORDER BY Time_Stamp DESC) AS ordinal_position,
a.ProviderID,
d.RowNum,
d.StartDate,
[AdditionalReports] * 5 AS AdditionalReports,
[UniqueReportRequests] * 15 AS UniqueReportsRequests,
[SurveyCompleted] * 30 as SurveyCompleted,
CASE WHEN b.ProviderID IS NULL THEN 0 ELSE 50 END as SubscriptionExists
FROM ProviderValueCard a
INNER JOIN date_range_cte d ON d.StartDate < Time_Stamp AND Time_Stamp <= d.EndDate
LEFT OUTER JOIN SubscriptionsTV b ON a.ProviderID = b.ProviderID
WHERE a.ProviderID = #ProviderID AND GroupID = 2
)
SELECT ProviderID, RowNum, StartDate, (AdditionalReports + UniqueReportsRequests + SurveyCompleted + SubscriptionExists) AS TotalScore
FROM main_cte
WHERE ordinal_position = 1
ORDER BY RowNum
Here's a couple of ways (psuedocode):
1 - Make a cte just like your existing one for each month you want to get. The only thing you need to change in each one is this line:
AND Time_Stamp BETWEEN DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 1, 0) AND DATEADD(DAY, -(DAY(GETDATE())), GETDATE())
For 2 months ago, you would change it to this:
AND Time_Stamp BETWEEN DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 2, 0) AND DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 1, 0)
and so on for the other months back.
2 - Referring to the same line in your cte above, change it to a -6 to get data for the past 6 months. Then include a MONTH(TimeStamp) column in your select list and group by it to get one row per month for the past 6 months.
I am looking to convert the following date
select (CONVERT(varchar(11), DATEADD(year, + 1,CONVERT(varchar(11), getdate(),111)))),datename(month,getdate()) for it returns 'jun 26 2015' ,'JUne'
I needed it to return as the following '2015/6' , June
This gives me what I want when using just get date
select CONVERT(varchar(7), getdate(), 111) = 2014/06
but I need it +1 year on my timewait field.
My actual code is as follows:
SELECT c.account_owner_by_SalesDiv, CONVERT(varchar(7), a.timeWait, 111)as rollingdate, DATENAME(MOnth, a.timeWait)
FROM SalesForce.dbo.SalesForceContact AS b INNER JOIN
Dossier_Replication.dbo.vw_SFAD_Contact_data AS c ON b.ContactID = c.CONTACTID__C RIGHT OUTER JOIN
satVRS.dbo.rptNECACallHistory AS a ON b.UserID = a.UserID_Caller
WHERE (b.Platform = 'HandsonVRS') AND (a.timeWait BETWEEN CONVERT(varchar(10), DATEADD(year, - 1, CONVERT(varchar, DATEADD(month, DATEDIFF(month, 0,
GETDATE()-1), 0), 120)), 120) AND CONVERT(varchar, DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0), 101)) AND (a.isReport = '1') AND (a.NECA_isReport = '1') AND
(a.ConvoTime > '0') AND (c.account_owner_by_SalesDiv IN ('Enterprise Account', 'National Account', 'Major Account', 'House Account', 'Inside Sales Account'))
GROUP BY c.account_owner_by_SalesDiv, CONVERT(varchar(7), a.timeWait, 111), DATENAME(MOnth, a.timeWait)
order by rollingdate
Thanks in advance.
This gives 2015/06, June:
SELECT
CONVERT(VARCHAR(7), DATEADD(YEAR,1,GETDATE()), 111) + ', ' + DATENAME(MONTH,GETDATE())
If you don't want the leading zero you could use the SUBSTRING function to trim it.