Recursive query? - sql

Hello everybody i'm currently stuck with a query for an ssrs report.
The database is a ticket registration for an helpdesk. So every day techs from the cds team log tickets. If they couldn't resolve the ticket they send it to an other team.
I'm looking for a query who retrace the backlog (non closed tickets) for each month and each team at the end of the month.
Ex :
May 26 17h ticket open by the helpdesk
May 27 8h ticket goes to Techsupport N2
June 3 ticket goes to Tech N3
July 2 ticket closed
I need to retrieve this :
Helpdesk May 0 June 0
N2 May 1 June 0
N3 May 0 June 1
database structure :
Table Appel
Noappel
C_equipe (last affected team)
Table actions
Noappel
Noaction
type_action (affect when goes to an other team Clos when closed)
C_equipe (team who done the action)
i made something based on a query found on the web but it works on weeks not months.
DECLARE #DR DATETIME
DECLARE #SM INTEGER
SET #SM=5
SET #DR=getdate()
SELECT T.* FROM (SELECT A.IDT_APPEL AS NOTICKET,
DEBUT.C_ACTION AS C_DEBUT,
FIN.C_ACTION AS C_FIN,
RS.DF_SEM AS F_TEST,
RS.NUM_SEMAINE AS NUM_SEMAINE,
E.L_EQUIPE AS EQUIPETICKET,
EP.L_EQUIPE AS EQUIPESUP,
A.C_UTIL_INT,
CONCAT(util.N_UTIL,' ',util.PRE_UTIL) AS INTERVENANT,
CASE
WHEN Datepart(ISO_WEEK, FIN.D_CREATION) = RS.NUM_SEMAINE
AND Datediff(DAY, FIN.D_CREATION, RS.DF_SEM) < 7
AND FIN.C_TACTION = 'SYS_EQUIPE'
AND Isnull(UTIL.C_ISIPARC, '0') <> '666' THEN 1
ELSE 0
END AS COND_TR,
CASE
WHEN Datepart(ISO_WEEK, FIN.D_CREATION) = RS.NUM_SEMAINE
AND Datediff(DAY, FIN.D_CREATION, RS.DF_SEM) < 7
AND FIN.C_TACTION = 'SYS_EQUIPE'
AND Isnull(UTIL.C_ISIPARC, '0') = '666' THEN 1
ELSE 0
END AS COND_REJ,
CASE
WHEN FIN.C_TACTION IN('SYS_CLOS_TECH','SYS_CLOS')
AND Datepart(ISO_WEEK, FIN.D_CREATION) = RS.NUM_SEMAINE
AND Datediff(DAY, FIN.D_CREATION, RS.DF_SEM) < 7 THEN 1
ELSE 0
END AS COND_CLOS,
CASE
WHEN Datepart(ISO_WEEK, DEBUT.D_CREATION) = RS.NUM_SEMAINE
AND Datediff(DAY, DEBUT.D_CREATION, RS.DF_SEM) < 7 THEN 1
ELSE 0
END AS NB_TICKET_ENTRE,
CASE
WHEN ( ( FIN.D_CREATION IS NULL
OR FIN.D_CREATION > RS.DF_SEM )
AND DEBUT.D_CREATION < RS.DF_SEM ) THEN ( CASE
WHEN Datediff(DAY, DEBUT.D_CREATION, RS.DF_SEM) - 2 < 5 THEN '05'
WHEN Datediff(DAY, DEBUT.D_CREATION, RS.DF_SEM) - 2 >= 5
AND Datediff(DAY, DEBUT.D_CREATION, RS.DF_SEM) - 2 < 10 THEN '10'
WHEN Datediff(DAY, DEBUT.D_CREATION, RS.DF_SEM) - 2 >= 10
AND Datediff(MONTH, DEBUT.D_CREATION, RS.DF_SEM) < 1 THEN '30'
WHEN Datediff(MONTH, DEBUT.D_CREATION, RS.DF_SEM) >= 1 THEN '30+'
ELSE NULL
END )
ELSE NULL
END AS F_NONCLOS,
CASE
WHEN Datepart(ISO_WEEK, FIN.D_CREATION) = RS.NUM_SEMAINE
AND Datediff(DAY, FIN.D_CREATION, RS.DF_SEM) < 7 THEN ( CASE
WHEN Datediff(DAY, DEBUT.D_CREATION, FIN.D_CREATION) < 1 THEN '01'
WHEN Datediff(DAY, DEBUT.D_CREATION, FIN.D_CREATION) >= 1
AND Datediff(DAY, DEBUT.D_CREATION, FIN.D_CREATION) < 2 THEN '02'
WHEN Datediff(DAY, DEBUT.D_CREATION, FIN.D_CREATION) >= 2
AND Datediff(DAY, DEBUT.D_CREATION, FIN.D_CREATION) < 5 THEN '05'
WHEN Datediff(DAY, DEBUT.D_CREATION, FIN.D_CREATION) >= 5
AND Datediff(DAY, DEBUT.D_CREATION, FIN.D_CREATION) < 15 THEN '15'
WHEN Datediff(DAY, DEBUT.D_CREATION, FIN.D_CREATION) >= 15 THEN '15+'
ELSE NULL
END )
ELSE NULL
END AS F_CLOS,
DEBUT.D_CREATION AS DEBUT,
FIN.D_CREATION AS FIN,
RS.YEAR AS YEARS
FROM APPEL A
INNER JOIN (SELECT B.NO_APPEL,
B.C_ACTION,
B.D_CREATION,
B.C_EQUIPE,
B.C_TACTION,
Lead(B.C_ACTION, 1)
OVER (
PARTITION BY B.NO_APPEL
ORDER BY B.C_ACTION) AS FIN_C_ACTION
FROM ACTIONS B WITH (NOLOCK)
WHERE B.C_TACTION IN ( 'SYS_EQUIPE', 'SYS_CLOS_TECH', 'SYS_REOUVERT','SYS_CLOS' )
AND ( CAST(B.D_CREATION AS DATE)< Dateadd(week, Datediff(week, 0, Dateadd(WEEK, 0, #DR)), 0) )) DEBUT
ON ( A.NO_APPEL = DEBUT.NO_APPEL
AND DEBUT.C_EQUIPE IN('ETUD_MET_BILIZI')
AND DEBUT.C_TACTION IN( 'SYS_EQUIPE', 'SYS_REOUVERT' ) )
LEFT JOIN ACTIONS FIN WITH (NOLOCK)
ON ( FIN.C_ACTION = DEBUT.FIN_C_ACTION )
LEFT JOIN UTILISATEUR UTIL WITH (NOLOCK)
ON ( UTIL.C_UTIL = FIN.C_UTIL )
INNER JOIN EQUIPE E WITH (NOLOCK)
ON DEBUT.C_EQUIPE = E.C_EQUIPE
INNER JOIN EQUIPE EP WITH (NOLOCK)
ON E.C_EQUIPE_PERE = EP.C_EQUIPE
INNER JOIN (SELECT DISTINCT Datepart(ISO_WEEK, P.D_JOUR) AS Num_semaine,
Dateadd(SECOND, 59, Dateadd(MINUTE, 59, Dateadd(HOUR, 23, Dateadd(DAY, -1, Dateadd(week, Datediff(week, 0, P.D_JOUR) + 1, 0))))) AS DF_SEM,
YEAR(P.D_JOUR) AS YEAR
FROM PLANNINGS P WITH (NOLOCK)
INNER JOIN TCALEND TC WITH (NOLOCK)
ON TC.C_TCALEND = P.C_TCALEND
AND TC.F_TCALENDSTD = 1
WHERE ( C_TPERIOD <> 3
AND C_TPERIOD <> 9 )) RS
ON ( ( FIN.D_CREATION > Dateadd(DAY, -7, RS.DF_SEM)
OR FIN.D_CREATION IS NULL )
AND (CAST( RS.DF_SEM AS DATE) >= Dateadd(week, Datediff(week, 0, Dateadd(WEEK, - #SM, #DR)), 0)
AND CAST(RS.DF_SEM AS DATE) <= Dateadd(week, Datediff(week, 0, Dateadd(WEEK, 0,#DR)), 0) ) )
WHERE (A.C_NATURE = 'INC' OR A.C_NATURE = 'DMD')
AND ( A.D_CLOTTECH >= Dateadd(week, Datediff(week, 0, Dateadd(WEEK, - #SM, #DR)), 0)
OR A.D_CLOTTECH IS NULL )
UNION
SELECT DISTINCT NULL IDT_APPEL,
NULL C_DEBUT,
NULL C_FIN,
Dateadd(SECOND, 59, Dateadd(MINUTE, 59, Dateadd(HOUR, 23, Dateadd(DAY, -1, Dateadd(week, Datediff(week, 0, P.D_JOUR) + 1, 0))))) AS DF_SEM,
Datepart(ISO_WEEK, P.D_JOUR) AS Num_semaine,
NULL EQUIPETICKET,
NULL EQUIPESUP,
NULL C_UTIL_INT,
NULL INTERVENANT,
0 COND_TR,
0 COND_REJ,
0 COND_CLOS,
0 NB_TICKET_ENTRE,
NULL F_NONCLOS,
NULL F_CLOS,
NULL,
NULL,
--YEAR(P.D_JOUR) AS YEARS
case when Datepart(ISO_WEEK, P.D_JOUR)=1 then YEAR(getdate()) ELSE YEAR(P.D_JOUR) end AS YEARS
FROM PLANNINGS P WITH (NOLOCK)
INNER JOIN TCALEND TC WITH (NOLOCK)
ON TC.C_TCALEND = P.C_TCALEND
AND TC.F_TCALENDSTD = 1
WHERE ( C_TPERIOD <> 3
AND C_TPERIOD <> 9 )
AND Dateadd(SECOND, 59, Dateadd(MINUTE, 59, Dateadd(HOUR, 23, Dateadd(DAY, -1, Dateadd(week, Datediff(week, 0, P.D_JOUR) + 1, 0))))) >= Dateadd(week, Datediff(week, 0, Dateadd(WEEK, - #SM, #DR)), 0)
AND Dateadd(SECOND, 59, Dateadd(MINUTE, 59, Dateadd(HOUR, 23, Dateadd(DAY, -1, Dateadd(week, Datediff(week, 0, P.D_JOUR) + 1, 0))))) <= Dateadd(week, Datediff(week, 0, Dateadd(WEEK, 0, #DR)), 0)) T ORDER BY T.YEARS ASC
Thanks

Related

Query multiple aggregations in a single row

I want a query that returns results from 3 months, 6 months and 12 months in their own column.
3 | 6 | 12
V1| V2| V3
I have a query that will give me any one of these results:
Code to get one value:
SELECT SUM(CONVERT(bigint,R.FileSize)) / (1024*1024) AS '3'
FROM Revisions R
JOIN Documents D ON D.DocumentID = R.DocumentID
WHERE R.Date BETWEEN dateadd(month, -3, GETDATE()) AND getdate()
Results:
3
205
I tried to embed the SQL query and combine them.
SELECT b.3, SUM(CONVERT(bigint,R.FileSize)) / (1024*1024) AS '6'
FROM Revisions R2
JOIN Documents D2 ON D2.DocumentID = R2.DocumentID
FULL OUTER JOIN b ON b.3 = 6
(SELECT SUM(CONVERT(bigint,R.FileSize)) / (1024*1024) AS '3'
FROM Revisions R
JOIN Documents D ON D.DocumentID = R.DocumentID
WHERE R.Date BETWEEN dateadd(month, -3, GETDATE()) AND getdate()) b
WHERE R2.Date BETWEEN dateadd(month, -6, GETDATE()) AND getdate();
I think you want conditional aggregation:
SELECT SUM(CASE WHEN R.Date BETWEEN dateadd(month, -3, GETDATE()) AND getdate()
THEN CONVERT(bigint, R.FileSize)) / (1024*1024)
END) AS filesize_3,
SUM(CASE WHEN R.Date BETWEEN dateadd(month, -6, GETDATE()) AND getdate()
THEN CONVERT(bigint, R.FileSize)) / (1024*1024)
END) AS filesize_6,
SUM(CASE WHEN R.Date BETWEEN dateadd(month, -9, GETDATE()) AND getdate()
THEN CONVERT(bigint, R.FileSize)) / (1024*1024)
END) AS filesize_9
FROM Revisions R JOIN
Documents D
ON D.DocumentID = R.DocumentID

Selecting multiple subqueries

I have subqueries that need to return different results. Each subqueries used different aggregate functions like SUM() AND COUNT(*). What I did is I encapsulate them with SELECT (SELECT subquery, SELECT subquery) not sure if this possible.
Expected result:
TwoYears
123
5
SELECT(
(SELECT
(SELECT SUM(AHT)
FROM
(
SELECT
CASE
WHEN DATEDIFF(year, [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[HireDate], GETDATE()) >= 2 AND (DATEDIFF(year, [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[HireDate], GETDATE())) <= 2 OR (DATEDIFF(year, [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[HireDate], GETDATE())) <= 1
THEN [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[Value]
END AS AHT
FROM [AgentProfile_CRT].[dbo].[uvw_AHTMaster] WHERE [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[Month] = 'January' AND [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[Year] = 2018 AND [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[AccountID] = 8 AND [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[LOBID] = 23
) f
WHERE AHT = AHT ) AS TwoYears),
(SELECT
(SELECT COUNT(*) AS TwoYears
FROM
(
SELECT
CASE
WHEN DATEDIFF(year, [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[HireDate], GETDATE()) >= 2 AND (DATEDIFF(year, [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[HireDate], GETDATE())) <= 2 OR (DATEDIFF(year, [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[HireDate], GETDATE())) <= 1
THEN 'Good'
END AS Result
FROM [AgentProfile_CRT].[dbo].[uvw_AHTMaster] WHERE [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[Month] = 'January' AND [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[Year] = 2018 AND [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[AccountID] = 8 AND [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[LOBID] = 23
) f
WHERE Result = 'Good') AS TwoYears)
) a
You need to make a union all and remove some of your subselects.
Like this:
SELECT SUM(AHT) as TwoYears
FROM (
SELECT CASE
WHEN DATEDIFF(year, [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[HireDate], GETDATE()) >= 2
AND (DATEDIFF(year, [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[HireDate], GETDATE())) <= 2
OR (DATEDIFF(year, [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[HireDate], GETDATE())) <= 1
THEN [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[Value]
END AS AHT
FROM [AgentProfile_CRT].[dbo].[uvw_AHTMaster]
WHERE [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[Month] = 'January'
AND [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[Year] = 2018
AND [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[AccountID] = 8
AND [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[LOBID] = 23
) f
WHERE AHT = AHT
union all
SELECT COUNT(*) AS TwoYears
FROM (
SELECT CASE
WHEN DATEDIFF(year, [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[HireDate], GETDATE()) >= 2
AND (DATEDIFF(year, [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[HireDate], GETDATE())) <= 2
OR (DATEDIFF(year, [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[HireDate], GETDATE())) <= 1
THEN 'Good'
END AS Result
FROM [AgentProfile_CRT].[dbo].[uvw_AHTMaster]
WHERE [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[Month] = 'January'
AND [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[Year] = 2018
AND [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[AccountID] = 8
AND [AgentProfile_CRT].[dbo].[uvw_AHTMaster].[LOBID] = 23
) f
WHERE Result = 'Good'

How to crosstab my query so months show in colums in SQL Server

IF OBJECT_ID('tempdb.dbo.#time') IS NOT NULL
DROP TABLE #time
DECLARE #StartDate DATETIME = '06/01/2015',
#StopDate DATETIME = '09/30/2015';
SELECT
DATEADD(MONTH, DATEDIFF(MONTH, 0, dmtrans.DTTDAT), 0) AS 'time',
dmtrans.DTACRO as 'Loc_Acronym',
dmloc.DLONAME as 'Location',
dmdoctr.DDRNPI as 'NPI_Number',
(COALESCE(dmdoctr.DDRNAME,'')+' '+COALESCE(dmdoctr.DDRTITL,'')) as Provider,
sum(dmtrans.DTCNTR) as 'Visits',
sum(RVU.TotalRVU) as 'Total_RVUs',
(nullif(sum(RVU.TotalRVU),0)/nullif(sum(dmtrans.DTCNTR),0)) as 'Avg_RVU'
INTO
#time
FROM
dmtrans
LEFT OUTER JOIN
dmloc ON dmtrans.DTACRO = dmloc.DLOACRO
AND dmtrans.DTLOC = dmloc.DLONUM
LEFT OUTER JOIN
cptxref ON dmtrans.DTPROC = cptxref.chcod
LEFT OUTER JOIN
dmdoctr ON dmtrans.DTACRO = dmdoctr.DDRACRO
AND dmtrans.DTLOC = dmdoctr.DDRLOC
AND dmtrans.DTRPTDR = dmdoctr.DDRNUM
LEFT OUTER JOIN
RVU ON cptxref.chmcd1 = RVU.cptcode
AND RVU.recordname = '2006'
WHERE
(dmtrans.DTTTYP = 'C' )
AND (dmtrans.DTTDAT >= #StartDate)
AND (dmtrans.DTTDAT <= #StopDate)
AND (dmtrans.DTMODF <> '*p')
AND (dmtrans.DTACRO = 'ROS')
GROUP BY
dmdoctr.DDRNAME, dmdoctr.DDRNPI, dmtrans.DTTDAT,
dmtrans.DTACRO, dmloc.DLONAME, dmdoctr.DDRTITL,
dmtrans.DTPCPNO, dmtrans.DTRPTDR, dmtrans.DTCNTR
ORDER BY
dmdoctr.DDRNAME, dmtrans.DTACRO, dmtrans.DTTDAT
IF OBJECT_ID('tempdb.dbo.#time2') IS NOT NULL
DROP TABLE #time2
Select
Time,
Loc_Acronym as 'Loc_Acronym',
Location as 'Location',
NPI_Number as NPI_Number,
Provider as Provider,
sum(Visits) as 'Visits',
sum(Total_RVUs) as 'Total_RVUs',
Round(nullif(sum(Total_RVUs),0)/nullif(sum(Visits),0),2) as 'Avg RVU',
DATENAME (M,[time]) as 'Month' into #time2
from
#time
group by
time, Loc_Acronym, Location, Provider,NPI_Number
order by
Provider
select *
from #time2
So I never work on a crosstab function just learn of it's existence thru a google search. So my current result:
Time Loc_Acronym Location NPI_Number Provider Visits Total_RVUs Avg RVU Month
2015-06-01 ROS LOVELACE REG MED CTR- ROSWELL 1538198924 ARRINGTON, ALAN H M.D. 1 4.01 4.010000 June
2015-07-01 ROS LOVELACE REG MED CTR- ROSWELL 1982631560 ATKINS, ARNOLD M.D. 1 4.01 4.010000 July
2015-09-01 ROS LOVELACE REG MED CTR- ROSWELL 1982631560 ATKINS, ARNOLD M.D. 1 1.64 1.640000 September
2015-06-01 ROS LOVELACE REG MED CTR- ROSWELL NULL CORRIZ, STEPHEN M D.O. 303 799.92 2.640000 June
2015-07-01 ROS LOVELACE REG MED CTR- ROSWELL NULL CORRIZ, STEPHEN M D.O. 211 571.48 2.710000 July
2015-08-01 ROS LOVELACE REG MED CTR- ROSWELL NULL CORRIZ, STEPHEN M D.O. 235 664.02 2.830000 August
2015-09-01 ROS LOVELACE REG MED CTR- ROSWELL NULL CORRIZ, STEPHEN M D.O. 257 691.11 2.690000 September
So my desired result is to keep the current columns but instead of having the months all in one column, I will like to for the months, I'll like to have it in the header row. How can I do this in my extensive drop tables.
Simply add conditional CASE/WHEN for each month to output Month Columns all in one select query. By the way, you did not mention what you want in those month columns. Below I use count but consider any other aggregates.
SELECT
DATEADD(MONTH, 0, DATEDIFF(MONTH, 0, dmtrans.DTTDAT)) AS 'time',
dmtrans.DTACRO as 'Loc_Acronym',
dmloc.DLONAME as 'Location',
dmdoctr.DDRNPI as 'NPI_Number',
(COALESCE(dmdoctr.DDRNAME,'')+' '+COALESCE(dmdoctr.DDRTITL,'')) as Provider,
sum(dmtrans.DTCNTR) as 'Visits',
sum(RVU.TotalRVU) as 'Total_RVUs',
(nullif(sum(RVU.TotalRVU),0)/nullif(sum(dmtrans.DTCNTR),0)) as 'Avg_RVU',
SUM(CASE WHEN DatePart(MONTH, dmtrans.DTTDAT) = 1 THEN 1 ELSE 0) As 'January',
SUM(CASE WHEN DatePart(MONTH, dmtrans.DTTDAT) = 2 THEN 1 ELSE 0) As 'February',
SUM(CASE WHEN DatePart(MONTH, dmtrans.DTTDAT) = 3 THEN 1 ELSE 0) As 'March',
SUM(CASE WHEN DatePart(MONTH, dmtrans.DTTDAT) = 4 THEN 1 ELSE 0) As 'April',
SUM(CASE WHEN DatePart(MONTH, dmtrans.DTTDAT) = 5 THEN 1 ELSE 0) As 'May',
SUM(CASE WHEN DatePart(MONTH, dmtrans.DTTDAT) = 6 THEN 1 ELSE 0) As 'June',
SUM(CASE WHEN DatePart(MONTH, dmtrans.DTTDAT) = 7 THEN 1 ELSE 0) As 'July',
SUM(CASE WHEN DatePart(MONTH, dmtrans.DTTDAT) = 8 THEN 1 ELSE 0) As 'August',
SUM(CASE WHEN DatePart(MONTH, dmtrans.DTTDAT) = 9 THEN 1 ELSE 0) As 'September',
SUM(CASE WHEN DatePart(MONTH, dmtrans.DTTDAT) = 10 THEN 1 ELSE 0) As 'October',
SUM(CASE WHEN DatePart(MONTH, dmtrans.DTTDAT) = 11 THEN 1 ELSE 0) As 'November',
SUM(CASE WHEN DatePart(MONTH, dmtrans.DTTDAT) = 12 THEN 1 ELSE 0) As 'December'
FROM
dmtrans
LEFT OUTER JOIN
dmloc ON dmtrans.DTACRO = dmloc.DLOACRO
AND dmtrans.DTLOC = dmloc.DLONUM
LEFT OUTER JOIN
cptxref ON dmtrans.DTPROC = cptxref.chcod
LEFT OUTER JOIN
dmdoctr ON dmtrans.DTACRO = dmdoctr.DDRACRO
AND dmtrans.DTLOC = dmdoctr.DDRLOC
AND dmtrans.DTRPTDR = dmdoctr.DDRNUM
LEFT OUTER JOIN
RVU ON cptxref.chmcd1 = RVU.cptcode
AND RVU.recordname = '2006'
WHERE (dmtrans.DTTTYP = 'C' )
AND (dmtrans.DTTDAT >= #StartDate)
AND (dmtrans.DTTDAT <= #StopDate)
AND (dmtrans.DTMODF <> '*p')
AND (dmtrans.DTACRO = 'ROS')
GROUP BY
dmdoctr.DDRNAME, dmdoctr.DDRNPI, dmtrans.DTTDAT,
dmtrans.DTACRO, dmloc.DLONAME, dmdoctr.DDRTITL,
dmtrans.DTPCPNO, dmtrans.DTRPTDR, dmtrans.DTCNTR
ORDER BY
dmdoctr.DDRNAME, dmtrans.DTACRO, dmtrans.DTTDAT
USE cfsdwhd;
WITH MyCTE
AS
(
SELECT Dateadd(MONTH, Datediff(MONTH, 0, dmtrans.DTTDAT), 0) AS StartOfMonth,
dmtrans.DTACRO AS 'Loc_Acronym',
dmloc.DLONAME AS 'Location',
dmdoctr.DDRNPI AS 'NPI_Number',
( COALESCE(dmdoctr.DDRNAME, '') + ' '
+ COALESCE(dmdoctr.DDRTITL, '') ) AS Provider,
Sum(dmtrans.DTCNTR) AS 'Visits',
Sum(RVU.TotalRVU) AS 'Total_RVUs',
ISNULL(( NULLIF(Sum(RVU.TotalRVU), 0) / NULLIF(Sum(dmtrans.DTCNTR), 0) ), 0.00) AS 'Avg_RVU'
FROM dmtrans
LEFT OUTER JOIN dmloc
ON dmtrans.DTACRO = dmloc.DLOACRO
AND dmtrans.DTLOC = dmloc.DLONUM
LEFT OUTER JOIN cptxref
ON dmtrans.DTPROC = cptxref.chcod
LEFT OUTER JOIN dmdoctr
ON dmtrans.DTACRO = dmdoctr.DDRACRO
AND dmtrans.DTLOC = dmdoctr.DDRLOC
AND dmtrans.DTRPTDR = dmdoctr.DDRNUM
LEFT OUTER JOIN RVU
ON cptxref.chmcd1 = RVU.cptcode
AND RVU.recordname = '2006'
WHERE ( dmtrans.DTTTYP = 'C' )
AND ( dmtrans.DTTDAT >= '05/01/2015')
AND ( dmtrans.DTTDAT <= '09/30/2015')
AND ( dmtrans.DTMODF <> '*p' )
AND ( dmtrans.DTACRO = 'MOR' )
GROUP BY dmtrans.DTACRO,
dmloc.DLONAME,
dmdoctr.DDRNPI,
( COALESCE(dmdoctr.DDRNAME, '') + ' '
+ COALESCE(dmdoctr.DDRTITL, '') ) ,
Dateadd(MONTH, Datediff(MONTH, 0, dmtrans.DTTDAT), 0)
)
SELECT 1 As SortOrder, T1.Loc_Acronym,T1.Location,T1.NPI_Number,T1.Provider,'Sum Of Visits' AS [Values],
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 1 THEN Visits ELSE 0 END) AS 'January',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 2 THEN Visits ELSE 0 END) AS 'February',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 3 THEN Visits ELSE 0 END) AS 'March',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 4 THEN Visits ELSE 0 END) AS 'April',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 5 THEN Visits ELSE 0 END) AS 'May',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 6 THEN Visits ELSE 0 END) AS 'June',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 7 THEN Visits ELSE 0 END) AS 'July',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 8 THEN Visits ELSE 0 END) AS 'August',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 9 THEN Visits ELSE 0 END) AS 'September',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 10 THEN Visits ELSE 0 END) AS 'October',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 11 THEN Visits ELSE 0 END) AS 'November',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 12 THEN Visits ELSE 0 END) AS 'December'
from mycte T1
GROUP BY T1.Loc_Acronym,T1.Location,T1.NPI_Number,T1.Provider
UNION ALL
SELECT 2 As SortOrder, T1.Loc_Acronym,T1.Location,T1.NPI_Number,T1.Provider,'Sum Of Total_RVUs' AS [Values],
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 1 THEN Total_RVUs ELSE 0 END) AS 'January',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 2 THEN Total_RVUs ELSE 0 END) AS 'February',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 3 THEN Total_RVUs ELSE 0 END) AS 'March',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 4 THEN Total_RVUs ELSE 0 END) AS 'April',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 5 THEN Total_RVUs ELSE 0 END) AS 'May',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 6 THEN Total_RVUs ELSE 0 END) AS 'June',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 7 THEN Total_RVUs ELSE 0 END) AS 'July',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 8 THEN Total_RVUs ELSE 0 END) AS 'August',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 9 THEN Total_RVUs ELSE 0 END) AS 'September',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 10 THEN Total_RVUs ELSE 0 END) AS 'October',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 11 THEN Total_RVUs ELSE 0 END) AS 'November',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 12 THEN Total_RVUs ELSE 0 END) AS 'December'
from mycte T1
GROUP BY T1.Loc_Acronym,T1.Location,T1.NPI_Number,T1.Provider
UNION ALL
SELECT 3 As SortOrder, T1.Loc_Acronym,T1.Location,T1.NPI_Number,T1.Provider,'Sum Of Avg RVU' AS [Values],
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 1 THEN Avg_RVU ELSE 0 END) AS 'January',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 2 THEN Avg_RVU ELSE 0 END) AS 'February',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 3 THEN Avg_RVU ELSE 0 END) AS 'March',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 4 THEN Avg_RVU ELSE 0 END) AS 'April',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 5 THEN Avg_RVU ELSE 0 END) AS 'May',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 6 THEN Avg_RVU ELSE 0 END) AS 'June',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 7 THEN Avg_RVU ELSE 0 END) AS 'July',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 8 THEN Avg_RVU ELSE 0 END) AS 'August',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 9 THEN Avg_RVU ELSE 0 END) AS 'September',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 10 THEN Avg_RVU ELSE 0 END) AS 'October',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 11 THEN Avg_RVU ELSE 0 END) AS 'November',
SUM(CASE WHEN DatePart(MONTH, DATEADD(MONTH, DATEDIFF(MONTH, 0, StartOfMonth), 0)) = 12 THEN Avg_RVU ELSE 0 END) AS 'December'
from mycte T1
GROUP BY T1.Loc_Acronym,T1.Location,T1.NPI_Number,T1.Provider
ORDER BY Loc_Acronym,Provider,SortOrder}
This is what I derived to get the desired result. Even though I wanted to include a case statement that was dynamic with my where clause dates that only outputted months in that range. I can live with the result. Thank you all for your input.

Combining SQL querys in to one query

Hi i have a set of querys for getting data
two counting rows for the day and two for night, what i would like is to combine these in to one query.
SELECT controllerID
,COUNT(CardID) AS GoodCountDay
FROM ReaderData
WHERE (
ReaderTime BETWEEN '08:00:00'
AND '20:00:00'
)
AND (CardID = 'fffffff0')
AND (DATEDIFF(DAY, DATEADD(DAY, - 0, CURRENT_TIMESTAMP), dtReading) = 0)
GROUP BY controllerID
SELECT controllerID
,COUNT(CardID) AS ScrapCountDay
FROM ReaderData
WHERE (
ReaderTime BETWEEN '08:00:00'
AND '20:00:00'
)
AND (CardID = '007CF00B')
AND (DATEDIFF(DAY, DATEADD(DAY, - 0, CURRENT_TIMESTAMP), dtReading) = 0)
GROUP BY controllerID
SELECT controllerID
,COUNT(CardID) AS GoodCountNight
FROM ReaderData
WHERE (dtReading >= DATEADD(hour, 20, DATEADD(day, - 1, CAST(CAST(GETDATE() AS DATE) AS DATETIME))))
AND (dtReading < DATEADD(hour, 8, CAST(CAST(GETDATE() AS DATE) AS DATETIME)))
GROUP BY controllerID
SELECT controllerID
,count(CardID) AS ScrapCountNight
FROM ReaderData
WHERE dtReading >= dateadd(hour, 20, dateadd(day, - 1, cast(cast(getdate() AS DATE) AS DATETIME)))
AND dtReading < dateadd(hour, 8, cast(cast(getdate() AS DATE) AS DATETIME))
AND (CardID = '007CF00B')
GROUP BY controllerID
All of these querys have the same out put which looks like this
controllerID GoodCountDay
2 207
28 245
30 267
33 314
35 471
37 65
38 17
40 175
Is there any way i can combine these in to one query so the out put will be such
controllerID GoodCountDay ScrapCountDay GoodCountNight ScrapCountNight
2 207 12 123 1
28 245 123
30 267
33 314
35 471
37 65
38 17
40 175
You can use conditional aggregation:
SELECT controllerID,
SUM(CASE WHEN ReaderTime BETWEEN '08:00:00' AND '20:00:00' AND
DATEDIFF(DAY, DATEADD(DAY, - 0, CURRENT_TIMESTAMP), dtReading) = 0) AND
CardID = 'fffffff0' THEN 1 ELSE 0 END) as GoodCountDay
SUM(CASE WHEN ReaderTime BETWEEN '08:00:00' AND '20:00:00' AND
DATEDIFF(DAY, DATEADD(DAY, - 0, CURRENT_TIMESTAMP), dtReading) = 0) AND
CardID = '007CF00B' THEN 1 ELSE 0 END) as ScrapCountDay,
SUM(CASE WHEN dtReading >= DATEADD(hour, 20, DATEADD(day, - 1, CAST(CAST(GETDATE() AS date) AS datetime)))) AND
(dtReading < DATEADD(hour, 8, CAST(CAST(GETDATE() AS date) AS datetime)) AND
CardID = 'fffffff0' THEN 1 ELSE 0 END) as GoodCountNight
SUM(CASE WHEN dtReading >= DATEADD(hour, 20, DATEADD(day, - 1, CAST(CAST(GETDATE() AS date) AS datetime)))) AND
(dtReading < DATEADD(hour, 8, CAST(CAST(GETDATE() AS date) AS datetime)) AND
CardID = '007CF00B' THEN 1 ELSE 0 END) as ScrapCountNight
FROM ReaderData
group by controllerID;

SQL- Date Diff- # of week in each month between two date periods

Problem: Display in columns the number of weeks in each month between two date periods (out to three months is fine for now). If possible, from the current day (Dynamic)
Where I currently am:
SELECT Q3.[Begin Date]
,Q3.[End Date]
,Q3.Diff_in_Year
,sum(CASE
WHEN Q3.Year_Counter = 0
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y1
,sum(CASE
WHEN Q3.Year_Counter = 1
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y2
,sum(CASE
WHEN Q3.Year_Counter = 2
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y3
,sum(CASE
WHEN Q3.Year_Counter = 3
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y4
,sum(CASE
WHEN Q3.Year_Counter = 4
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y5
,sum(CASE
WHEN Q3.Year_Counter = 5
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y6
,sum(CASE
WHEN Q3.Year_Counter = 6
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y7
,sum(CASE
WHEN Q3.Year_Counter = 7
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y8
,sum(CASE
WHEN Q3.Year_Counter = 8
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y9
,sum(CASE
WHEN Q3.Year_Counter = 9
THEN datediff(mm, Q3.y_start, Q3.y_end) + 1
ELSE 0
END) Y10
FROM (
SELECT Q1.[Begin Date]
,Q1.[End Date]
,Q1.years Diff_in_Year
,Q2.number AS Year_Counter
,(
CASE
WHEN Q2.number = 0
THEN Q1.[Begin Date]
ELSE dateadd(yy, datediff(yy, 0, dateadd(yy, q2.number, q1.[Begin Date])), 0)
END
) AS y_Start
,(
CASE
WHEN ((Q1.years - 1) = Q2.number)
THEN Q1.[End Date]
ELSE DATEADD(yy, DATEDIFF(yy, 0, dateadd(yy, q2.number + 1, q1.[Begin Date]) + 1), - 1)
END
) AS y_End
,Year(Q1.[Begin Date]) + Q2.number YearInYYYY
FROM (
SELECT [Begin Date]
,[End Date]
,DATEDIFF(year, [Begin Date], [End Date]) + 1 AS years
FROM my dates
) Q1
INNER JOIN master..spt_values Q2 ON Q2.type = 'P'
AND Q2.number < Q1.years
) Q3
GROUP BY Q3.[Begin Date]
,Q3.[End Date]
,q3.Diff_in_Year
How the current code works: Given a date range, the number of months in each year between two dates. IE 1/1/2014 - 1/18/2015 would give two columns "2014" and 2015" the value of 2014 is 12 and the value of 2015 is 1 signifying that there are 13 months between the specified dates.
What I am hoping to achieve is something similar to
Start Date End Date Month 1 Month 2 Month 3
-----------------------------------------------------
1/1/2014 3/8/2014 4 4 1
Dynamic SQL solutions aside (search for dynamic pivot in TSQL), I whipped up a couple of answers. Since your question is unclear whether you want weeks or months, I put together a quick one for each.
Months Example Here:
declare #startdate date = '1/1/2014', #enddate date = '3/1/2015'
select p.*
from (
select #startdate as StartDate, #enddate as EndDate, right(convert(varchar,(dateadd(mm,RowID-1,#startdate)),105),4) [Group]
from (
select *, row_number()over(order by name) as RowID
from master..spt_values
) d
where d.RowID <= datediff(mm, #startdate, #enddate)
) t
pivot (
count([Group]) for [Group] in (
[2014],[2015]
)
) p
Weeks Example Here:
declare #startdate date = '1/1/2014', #enddate date = '3/1/2015'
select p.*
from (
select #startdate as StartDate, #enddate as EndDate, right(convert(varchar,(dateadd(ww,RowID-1,#startdate)),105),7) [Group]
from (
select *, row_number()over(order by name) as RowID
from master..spt_values
) d
where d.RowID <= datediff(ww, #startdate, #enddate)
) t
pivot (
count([Group]) for [Group] in (
[01-2014]
, [02-2014]
, [03-2014]
, [04-2014]
, [05-2014]
, [06-2014]
, [07-2014]
, [08-2014]
, [09-2014]
, [10-2014]
, [11-2014]
, [12-2014]
, [01-2015]
, [02-2015]
, [03-2015]
)
) p