When 'Select All' Parameter ticked all data is not showing - sql

This is a glimpse of what my report look likes, a series of charts, where you can select a country and a date range of either 12 months rolling or 36 months rolling.
The report is working ok in regards to selecting one country and seeing the different data within the 12 or 36 months date range.
The problem comes when I 'Select All' countries. What I want is the totals of all the countries to be represented on the graphs. As you see below, with all countries selected the data on the graph has not changed from the image above.
The Country parameter
This is my stored procedure
ALTER PROCEDURE [name] #Country VARCHAR(max)
,#DateRange VARCHAR(max)
AS
BEGIN
SELECT country
,[yyyy-mm]
,[12Months]
,[36Months]
,[Population]
,[Employed]
FROM (
SELECT CASE [countryID]
WHEN '800002'
THEN 'UK'
WHEN '800003'
THEN 'France'
WHEN '800004'
THEN 'Germany'
ELSE 'N/A'
END AS country
,Convert(CHAR(7), [DateTimeOfCall], 121) "yyyy-mm"
,CASE
WHEN datetimeofcall BETWEEN Dateadd(Month, Datediff(Month, 0, DATEADD(m, - 12, current_timestamp)), 0)
AND Dateadd(Month, Datediff(Month, 0, DATEADD(m, 0, current_timestamp)), 0)
THEN 'y'
ELSE 'n'
END AS [12Months]
,CASE
WHEN datetimeofcall BETWEEN Dateadd(Month, Datediff(Month, 0, DATEADD(m, - 36, current_timestamp)), 0)
AND Dateadd(Month, Datediff(Month, 0, DATEADD(m, 0, current_timestamp)), 0)
THEN 'y'
ELSE 'n'
END AS [36Months]
,sum(CASE
WHEN [CategoryID] = '180003'
AND [CauseID] IN (
'700002'
,'700003'
)
AND [TypeID] = '100002'
AND [PopTypeID] BETWEEN '170002'
AND '170019'
THEN 1
ELSE 0
END) Population
,sum(CASE
WHEN [EmpID] = '210002'
THEN 1
ELSE 0
END) AS Employed
FROM [dbo].[country]
WHERE STATUS = '1'
GROUP BY [countryID]
,Convert(CHAR(7), [DateTimeOfCall], 121)
,CASE
WHEN datetimeofcall BETWEEN Dateadd(Month, Datediff(Month, 0, DATEADD(m, - 12, current_timestamp)), 0)
AND Dateadd(Month, Datediff(Month, 0, DATEADD(m, 0, current_timestamp)), 0)
THEN 'y'
ELSE 'n'
END
,CASE
WHEN datetimeofcall BETWEEN Dateadd(Month, Datediff(Month, 0, DATEADD(m, - 36, current_timestamp)), 0)
AND Dateadd(Month, Datediff(Month, 0, DATEADD(m, 0, current_timestamp)), 0)
THEN 'y'
ELSE 'n'
END
) a
WHERE country in (#country)
AND (
(
#DateRange = 12
AND [12Months] = 'Y'
)
OR (
#DateRange = 36
AND [36Months] = 'Y'
)
)
END
And this is what the output is
country yyyy-mm Population Employed 12months 36months
uk 2016-06 56 43 y y
france 2016-06 40 22 y y
Germany 2016-06 73 32 y y
uk 2015-06 45 10 n y
france 2015-06 30 11 n y
Germany 2015-06 76 56 n y
AND SO ON......
All help appreciated, thank you.

Related

Recursive query?

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

Count individual days worked in a month excluding holidays and sick leaves

I need to get for each user how many days of the week they worked (in a month). I have a table storing the date range in which they didn't work (sick leave) and a tally table storing workdays.
ausentismoT stores the non worked days as date ranges, the table looks like this
user ini fin --ini = start date | fin = end date
---------------------------
john 06/05/2019 06/05/2019
john 13/05/2019 13/05/2019
john 20/05/2019 24/05/2019
Tally table, storing every day of the month and marking their status as holiday:
IDCal fechaValor numDiaSemana nomDia nomMes semanaAno diaJuliano feriadoBancario feriadoNombre
---------------------------------------------------------------------------------------------
20190502 2019-05-02 00:00:00.000 4 Jueves Mayo 18 122 0 NULL
20190503 2019-05-03 00:00:00.000 5 Viernes Mayo 18 123 0 NULL
20190504 2019-05-04 00:00:00.000 6 Sábado Mayo 18 124 1 Weekend
My code, which I know the logic is wrong, I ""try"" to exclude both holidays and non worked days but the results are 0 in all columns:
SELECT T.RUT_DV,
T.USER,
DIAS_HAB_MES = (SELECT COUNT(CONVERT(INT,feriadoBancario,112)) AS D FROM CALENDAR C WHERE feriadoBancario=0 AND CONVERT(NVARCHAR(6),C.fechaValor,112) = CONVERT(NVARCHAR(6),GETDATE(),112)),
LUNES = (SELECT COUNT(CONVERT(INT,feriadoBancario,112)) AS D FROM CALENDAR C
WHERE numDiaSemana=1 AND feriadoBancario = 0 AND (FECHAVALOR BETWEEN DATEADD(MM, DATEDIFF(MM, 0, GETDATE())-1, 0) AND T2.INI) AND FECHAVALOR BETWEEN DATEADD(MM, DATEDIFF(MM, 0, getdate()), 0)-1 AND T2.FIN),
MARTES = (SELECT COUNT(CONVERT(INT,feriadoBancario,112)) AS D FROM CALENDAR C
WHERE numDiaSemana=2 AND feriadoBancario = 0 AND (FECHAVALOR BETWEEN DATEADD(MM, DATEDIFF(MM, 0, GETDATE())-1, 0) AND T2.INI) AND FECHAVALOR BETWEEN DATEADD(MM, DATEDIFF(MM, 0, getdate()), 0)-1 AND T2.FIN),
MIERCOLES = (SELECT COUNT(CONVERT(INT,feriadoBancario,112)) AS D FROM CALENDAR C
WHERE numDiaSemana=3 AND feriadoBancario = 0 AND (FECHAVALOR BETWEEN DATEADD(MM, DATEDIFF(MM, 0, GETDATE())-1, 0) AND T2.INI) AND FECHAVALOR BETWEEN DATEADD(MM, DATEDIFF(MM, 0, getdate()), 0)-1 AND T2.FIN),
JUEVES = (SELECT COUNT(CONVERT(INT,feriadoBancario,112)) AS D FROM CALENDAR C
WHERE numDiaSemana=4 AND feriadoBancario = 0 AND (FECHAVALOR BETWEEN DATEADD(MM, DATEDIFF(MM, 0, GETDATE())-1, 0) AND T2.INI) AND FECHAVALOR BETWEEN DATEADD(MM, DATEDIFF(MM, 0, getdate()), 0)-1 AND T2.FIN),
VIERNES = (SELECT COUNT(CONVERT(INT,feriadoBancario,112)) AS D FROM CALENDAR C
WHERE numDiaSemana=5 AND feriadoBancario = 0 AND (FECHAVALOR BETWEEN DATEADD(MM, DATEDIFF(MM, 0, GETDATE())-1, 0) AND T2.INI) AND FECHAVALOR BETWEEN DATEADD(MM, DATEDIFF(MM, 0, getdate()), 0)-1 AND T2.FIN)
FROM dotacionAD T -- BASE TABLE
LEFT JOIN ausentismoT T2 ON T.RUT_DV = REPLACE(T2.RUT_DV,'.','')
Results are this:
NOM_COL DIAS_HAB_MES LUNES MARTES MIERCOLES JUEVES VIERNES
-------------------------------------------------------------------
JOHN 20 0 0 0 0 0
For the same case it should display this:
NOM_COL DIAS_HAB_MES LUNES MARTES MIERCOLES JUEVES VIERNES
-------------------------------------------------------------------
JOHN 20 1 3 3 4 4
I believe you have done an error when copy-pasting the dateadd/datediff a second time.
At the time I write this answer, my local getdate() would return 6 June 2019.
Your first condition is:
FECHAVALOR BETWEEN DATEADD(MM, DATEDIFF(MM, 0, GETDATE())-1, 0) AND T2.INI
This formula truncates the current date to month level, and also substracts one month. Thus, if I run it now, I will get 1 May 2019. All your ini are after this, so OK.
Your second condition is:
FECHAVALOR BETWEEN DATEADD(MM, DATEDIFF(MM, 0, getdate()), 0)-1 AND T2.FIN
This formula truncates the current date to month level, does not substract a month, but in the end it substracts a day. Thus, if I run it now, I will get 2 June 2019. None of your fin are later than that, and that's why you get zero everywhere.
Now I'm not sure what you intend to see, but two BETWEENs seem strange. If you want the last 2 months that are in ausentismoT, I would write it like this:
FECHAVALOR >= DATEADD(MM, DATEDIFF(MM, 0, GETDATE())-1, 0)
AND
FECHAVALOR BETWEEN T2.INI and T2.FIN
This should help get you started. It's not entirely clear if you've provided all the information though.
select
t.user, count(*) as dia_hab_mes,
count(case when numDiaSemana = 1 then 1 end) as lunes,
...
from
users as u cross join calendar as c
left outer join ausentismoT as a
on c.<date> between a.ini and a.fin and a.user = t.user
where c.<date> ... /* filter dates for desired month */
and feriadoBancario = 0
group by u.user;

efficient way to write this query - audit histroy on created and modified

just wondering if there is a better and more efficient way of creating this query as the below is taking a long time as this query is being run for every table in the database catalogue. Thank you
Select N'MSCRM_REPORTING' As [Database], N'dbo' As [Schema], N'apuk_erqanswerBase' As [Table], N'ModifiedOn' As ChangeType,
sum(case when DATEADD(dd, DATEDIFF(dd, 0,ModifiedOn), 0) between DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0) -7 AND DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0) THEN 1 ELSE 0 END) [0-7 Days],
sum(case when DATEADD(dd, DATEDIFF(dd, 0,ModifiedOn), 0) between DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)-28 AND DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)- 8 THEN 1 ELSE 0 END) [8-28 Days],
sum(case when DATEADD(dd, DATEDIFF(dd, 0,ModifiedOn), 0) between DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)-84 AND DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)-29 THEN 1 ELSE 0 END) [29-84 Days],
sum(case when DATEADD(dd, DATEDIFF(dd, 0,ModifiedOn), 0) between DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)-182 AND DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)-85 THEN 1 ELSE 0 END) [85-182 Days],
sum(case when DATEADD(dd, DATEDIFF(dd, 0, ModifiedOn), 0) BETWEEN convert(datetime,0) and DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0) - 183 THEN 1 ELSE 0 END) [183+],
sum(case when ModifiedOn is null then 1 else 0 end) [NullRows],
count(*) as [RowCount]
From MSCRM_REPORTING.dbo.apuk_erqanswerBase
Having multiple DATEDIFFs will be costly, so why not try getting the difference between the dates in a subquery and using that within the SELECT:
Select N'MSCRM_REPORTING' As [Database], N'dbo' As [Schema], N'apuk_erqanswerBase' As [Table], N'ModifiedOn' As ChangeType,
sum(case when a.Days BETWEEN 0 AND 7 THEN 1 ELSE 0 END) [0-7 Days],
sum(case when a.Days BETWEEN 8 AND 28 THEN 1 ELSE 0 END) [8-28 Days],
sum(case when a.Days BETWEEN 29 AND 84 THEN 1 ELSE 0 END) [29-84 Days],
sum(case when a.Days BETWEEN 85 AND 182 THEN 1 ELSE 0 END) [85-182 Days],
sum(case when a.Days >= 183 THEN 1 ELSE 0 END) [183+],
sum(case when ModifiedOn is null then 1 else 0 end) [NullRows],
count(*) as [RowCount]
From
(
Select DATEDIFF(dd, ModifiedOn, getdate()) AS [Days],
ModifiedOn
From MSCRM_REPORTING.dbo.apuk_erqanswerBase
) a
You can try this as well:
Select N'MSCRM_REPORTING' As [Database],
N'dbo' As [Schema],
N'apuk_erqanswerBase' As [Table],
N'ModifiedOn' As ChangeType,
sum(case when DATEDIFF(dd, ModifiedOn, getdate()) BETWEEN 0 AND 7 THEN 1 ELSE 0 END) [0-7 Days],
sum(case when DATEDIFF(dd, ModifiedOn, getdate()) BETWEEN 8 AND 28 THEN 1 ELSE 0 END) [8-28 Days],
sum(case when DATEDIFF(dd, ModifiedOn, getdate()) BETWEEN 29 AND 84 THEN 1 ELSE 0 END) [29-84 Days],
---------------------
from MSCRM_REPORTING.dbo.apuk_erqanswerBase

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.

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