How to get accumulated-monthly data using query - sql

When I run this query, it should display 3 rows of result under DAY column (210301, 201302, SUM).But for some reason, it only shows SUM row under DAY column. Idea is that '201301' row accumulates 31 days of data in January.
Can anyone point me out why they don't show up?
SELECT X.*
FROM
(
SELECT
(CASE
WHEN DAY.DAY = 'SUM' THEN DAY.DAY
ELSE
TO_CHAR (TO_DATE (DAY.DAY, 'YYYY-MM'), 'YYYYMM')
END
) AS DAY,
MNOT.SUM_STD_CNT AS MNOT_CNT,
RSC.MOVIE_500K AS MOVIE_500K_CNT,
RSC.MOVIE_1M AS MOVIE_1M_CNT,
RSC.MOVIE AS MOVIE_CNT,
RSC.EXAM AS EXAM_CNT,
RSC.WEB AS WEB_CNT,
RSC.IMG AS IMG_CNT,
RSC.INTERRAC AS INTERRACTIVE_CNT,
RSC.DOC AS DOC_CNT,
MNOT.SUM_STD_CNT + RSC.MOVIE_500K + RSC.MOVIE_1M + RSC.MOVIE + RSC.EXAM + RSC.WEB + RSC.IMG + RSC.INTERRAC + RSC.DOC TOT_CNT
FROM
/* DATES */
(SELECT TO_CHAR(ADD_MONTHS(TO_DATE('201301','YYYYMM'),LEVEL-1), 'YYYYMM') AS DAY
FROM DUAL
CONNECT BY ADD_MONTHS(TO_DATE('201301','YYYYMM'),LEVEL-1 ) <= TO_DATE('201302', 'YYYYMM')
UNION ALL
SELECT 'SUM' FROM DUAL
) DAY LEFT OUTER JOIN
/* RESOURCE */
(
SELECT
NVL(DT_G.COMM_DT, 'SUM') COMM_DT
,NVL(SUM(DT_G.MOVIE_500K), 0) AS MOVIE_500K
,NVL(SUM(DT_G.MOVIE_1M), 0) AS MOVIE_1M
,NVL(SUM(DT_G.MOVIE), 0) AS MOVIE
,NVL(SUM(DT_G.EXAM), 0) AS EXAM
,NVL(SUM(DT_G.DOC), 0) AS DOC
,NVL(SUM(DT_G.IMG), 0) AS IMG
,NVL(SUM(DT_G.WEB), 0) AS WEB
,NVL(SUM(DT_G.INTERRAC), 0) AS INTERRAC
FROM
(
SELECT
COMM_DT
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP10' THEN SUMT.SUM_500K END MOVIE_500K
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP10' THEN SUMT.SUM_1M END AS MOVIE_1M
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP10' THEN SUMT.SUM_500K+SUMT.SUM_1M END AS MOVIE
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP11' THEN SUMT.SUM_STD_CNT END AS EXAM
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP12' THEN SUMT.SUM_STD_CNT END AS DOC
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP13' THEN SUMT.SUM_STD_CNT END AS IMG
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP14' THEN SUMT.SUM_STD_CNT END AS WEB
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP01' THEN SUMT.SUM_STD_CNT END AS INTERRAC
FROM (
SELECT RSC_TP_DSCD, SUM(STDY_CNT) AS SUM_STD_CNT, SUM(MOVIE_STDY_CNT_N1M) AS SUM_1M, SUM(MOVIE_STDY_CNT_N500K) AS SUM_500K, COMM_DT
FROM (
SELECT RSC_SNO, STDY_CNT, MOVIE_STDY_CNT_N1M, MOVIE_STDY_CNT_N500K, COMM_DT
FROM LRMS.V_EBSM_PKG_RSC_COMM_CNT
WHERE PKG_SNO = 0 AND RSC_SNO != 0
AND COMM_DT BETWEEN TO_CHAR(TO_DATE('201301', 'YYYY-MM'), 'YYYYMM') AND TO_CHAR(TO_DATE('201311', 'YYYY-MM'), 'YYYYMMDD')
) CNT
LEFT OUTER JOIN LRMS.V_LRRM_RSC RSC ON CNT.RSC_SNO = RSC.RSC_SNO
GROUP BY RSC_TP_DSCD, COMM_DT
) SUMT
) DT_G
GROUP BY ROLLUP(DT_G.COMM_DT)
) RSC ON DAY.DAY = RSC.COMM_DT
/* MNOTE */
LEFT OUTER JOIN
(
SELECT NVL(SUM(STDY_CNT), 0) AS SUM_STD_CNT, NVL(COMM_DT, 'SUM') COMM_DT
FROM LRMS.V_EBSM_PKG_RSC_COMM_CNT
WHERE PKG_SNO != 0 AND RSC_SNO = 0
AND COMM_DT BETWEEN TO_CHAR(TO_DATE('201301', 'YYYY-MM'), 'YYYYMM') AND TO_CHAR(TO_DATE('201306', 'YYYY-MM'), 'YYYYMM')
GROUP BY ROLLUP(COMM_DT)
) MNOT ON DAY.DAY = MNOT.COMM_DT
) X
WHERE 1=1
and X.TOT_CNT IS NOT NULL

This may be because of the null values in the sum field TOT_CNT
change the line
MNOT.SUM_STD_CNT + RSC.MOVIE_500K + RSC.MOVIE_1M + RSC.MOVIE + RSC.EXAM + RSC.WEB + RSC.IMG + RSC.INTERRAC + RSC.DOC TOT_CNT
to
nvl(MNOT.SUM_STD_CNT,0) + nvl(RSC.MOVIE_500K,0) + nvl(RSC.MOVIE_1M,0) + nvl(RSC.MOVIE,0) + nvl(RSC.EXAM,0) + nvl(RSC.WEB,0) + nvl(RSC.IMG,0) + nvl(RSC.INTERRAC,0) + nvl(RSC.DOC,0) AS TOT_CNT
and try

Related

How to get column total for a table with two pivots

I have created a table joining two table having two pivots, Now I intend to get the total of all the column values for each row.
Below is my code which I am currently working on:
SELECT
*
FROM
(SELECT
time_tracker.date,
Users.FirstName + ' ' + Users.LastName AS username,
(CASE
WHEN ((datepart(hour, chk_in)) >= 12 OR
(datepart(hour, chk_out)) < 16)
THEN 0.5
ELSE 1
END) AS late,
TypeOfLeaves.leave_type, Userleavetyp.no_of_days
FROM
Users
INNER JOIN
time_tracker ON Users.ID = time_tracker.fk_userid
INNER JOIN
Userleavetyp ON Users.ID = Userleavetyp.fk_user
INNER JOIN
TypeOfLeaves ON Userleavetyp.fk_tol = TypeOfLeaves.ID
WHERE
(Users.FK_Status = 1)) AS P
For month days
PIVOT
(SUM(late) FOR date IN ("2018-01-01", "2018-01-02", "2018-01-03", "2018-01-04", "2018-01-05", "2018-01-06", "2018-01-07", "2018-01-08", "2018-01-09", "2018-01-10", "2018-01-11", "2018-01-12", "2018-01-13", "2018-01-14", "2018-01-15", "2018-01-16", "2018-01-17", "2018-01-18", "2018-01-19", "2018-01-20", "2018-01-21", "2018-01-22", "2018-01-23", "2018-01-24", "2018-01-25", "2018-01-26", "2018-01-27", "2018-01-28", "2018-01-29", "2018-01-30", "2018-01-31")
) AS pv1
For leave type
PIVOT
(SUM(no_of_days)
FOR leave_type IN ([Casual Leave], [Paid Leave], [Complimentary Leave])) AS pv2
I want the desired result to be something like this
enter image description here
Two things you can do:
Sum all pivoted columns: add an additional expression that sums all results. Change:
SELECT
*
FROM
--...
To:
SELECT
*,
Total = ISNULL([2018-01-01], 0)
+ ISNULL([2018-01-02], 0)
+ ISNULL([2018-01-03], 0)
+ ISNULL([2018-01-04], 0)
+ ISNULL([2018-01-05], 0)
+ ISNULL([2018-01-06], 0)
+ ISNULL([2018-01-07], 0)
+ ISNULL([2018-01-08], 0)
+ ISNULL([2018-01-09], 0)
+ ISNULL([2018-01-10], 0)
+ ISNULL([2018-01-11], 0)
+ ISNULL([2018-01-12], 0)
+ ISNULL([2018-01-13], 0)
+ ISNULL([2018-01-14], 0)
+ ISNULL([2018-01-15], 0)
+ ISNULL([2018-01-16], 0)
+ ISNULL([2018-01-17], 0)
+ ISNULL([2018-01-18], 0)
+ ISNULL([2018-01-19], 0)
+ ISNULL([2018-01-20], 0)
+ ISNULL([2018-01-21], 0)
+ ISNULL([2018-01-22], 0)
+ ISNULL([2018-01-23], 0)
+ ISNULL([2018-01-24], 0)
+ ISNULL([2018-01-25], 0)
+ ISNULL([2018-01-26], 0)
+ ISNULL([2018-01-27], 0)
+ ISNULL([2018-01-28], 0)
+ ISNULL([2018-01-29], 0)
+ ISNULL([2018-01-30], 0)
+ ISNULL([2018-01-31], 0)
FROM
--...
Calculate the total on another subquery and join at the end to retrieve the total:
;WITH ToPivot AS
(
SELECT
time_tracker.date,
Users.FirstName + ' ' + Users.LastName AS username,
(CASE
WHEN ((datepart(hour, chk_in)) >= 12 OR
(datepart(hour, chk_out)) < 16)
THEN 0.5
ELSE 1
END) AS late,
TypeOfLeaves.leave_type,
Userleavetyp.no_of_days
FROM
Users
INNER JOIN
time_tracker ON Users.ID = time_tracker.fk_userid
INNER JOIN
Userleavetyp ON Users.ID = Userleavetyp.fk_user
INNER JOIN
TypeOfLeaves ON Userleavetyp.fk_tol = TypeOfLeaves.ID
WHERE
(Users.FK_Status = 1)
),
LateTotals AS
(
SELECT
T.username,
Total = SUM(late)
FROM
ToPivot AS T
WHERE
T.date IN ('2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04', '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08', '2018-01-09', '2018-01-10', '2018-01-11', '2018-01-12', '2018-01-13', '2018-01-14', '2018-01-15', '2018-01-16', '2018-01-17', '2018-01-18', '2018-01-19', '2018-01-20', '2018-01-21', '2018-01-22', '2018-01-23', '2018-01-24', '2018-01-25', '2018-01-26', '2018-01-27', '2018-01-28', '2018-01-29', '2018-01-30', '2018-01-31')
GROUP BY
T.username
)
SELECT
PV2.*,
L.Total
FROM
ToPivot AS P
PIVOT
(SUM(late) FOR date IN ("2018-01-01", "2018-01-02", "2018-01-03", "2018-01-04", "2018-01-05", "2018-01-06", "2018-01-07", "2018-01-08", "2018-01-09", "2018-01-10", "2018-01-11", "2018-01-12", "2018-01-13", "2018-01-14", "2018-01-15", "2018-01-16", "2018-01-17", "2018-01-18", "2018-01-19", "2018-01-20", "2018-01-21", "2018-01-22", "2018-01-23", "2018-01-24", "2018-01-25", "2018-01-26", "2018-01-27", "2018-01-28", "2018-01-29", "2018-01-30", "2018-01-31")
) AS pv1
PIVOT
(SUM(no_of_days)
FOR leave_type IN ([Casual Leave], [Paid Leave], [Complimentary Leave])
) AS pv2
LEFT JOIN LateTotals AS L ON L.username = pv2.username

SQL Query not producing 'Disabled' jobs within the results, alongside 'Failed' jobs

I have the following code for a SQL Query I'm working on..
DECLARE #Date datetime
SET #Date = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
DECLARE #jobHistory TABLE
(
job_id UNIQUEIDENTIFIER
, success INT
, cancel INT
, fail INT
, retry INT
, last_execution_id INT
, last_duration CHAR(8)
, last_execution_start DATETIME
);
WITH lastExecution
AS
(
SELECT job_id
, MAX(instance_id) AS last_instance_id
FROM msdb.dbo.sysjobhistory
WHERE step_id = 0
GROUP BY job_id
)
INSERT INTO #jobHistory
SELECT sjh.job_id
, SUM(CASE WHEN sjh.run_status = 1 AND step_id = 0 THEN 1 ELSE 0 END) AS success
, SUM(CASE WHEN sjh.run_status = 3 AND step_id = 0 THEN 1 ELSE 0 END) AS cancel
, SUM(CASE WHEN sjh.run_status = 0 AND step_id = 0 THEN 1 ELSE 0 END) AS fail
, SUM(CASE WHEN sjh.run_status = 2 THEN 1 ELSE 0 END) AS retry
, MAX(CASE WHEN sjh.step_id = 0 THEN instance_id ELSE NULL END) last_execution_id
, SUBSTRING(CAST(MAX(CASE WHEN le.job_id IS NOT NULL THEN sjh.run_duration ELSE NULL END) + 1000000 AS VARCHAR(7)),2,2) + ':'
+ SUBSTRING(CAST(MAX(CASE WHEN le.job_id IS NOT NULL THEN sjh.run_duration ELSE NULL END) + 1000000 AS VARCHAR(7)),4,2) + ':'
+ SUBSTRING(CAST(MAX(CASE WHEN le.job_id IS NOT NULL THEN sjh.run_duration ELSE NULL END) + 1000000 AS VARCHAR(7)),6,2)
AS last_duration
, MAX(CASE WHEN le.last_instance_id IS NOT NULL THEN
CONVERT(datetime, RTRIM(run_date))
+ ((run_time / 10000 * 3600)
+ ((run_time % 10000) / 100 * 60)
+ (run_time % 10000) % 100) / (86399.9964)
ELSE '1900-01-01' END) AS last_execution_start
FROM msdb.dbo.sysjobhistory AS sjh
LEFT JOIN lastExecution AS le
ON sjh.job_id = le.job_id
AND sjh.instance_id = le.last_instance_id
GROUP BY sjh.job_id;
DECLARE #weekDay TABLE (
mask INT
, maskValue VARCHAR(32)
);
INSERT INTO #weekDay
SELECT 1, 'Sunday' UNION ALL
SELECT 2, 'Monday' UNION ALL
SELECT 4, 'Tuesday' UNION ALL
SELECT 8, 'Wednesday' UNION ALL
SELECT 16, 'Thursday' UNION ALL
SELECT 32, 'Friday' UNION ALL
SELECT 64, 'Saturday';
WITH myCTE
AS(
SELECT sched.name AS 'scheduleName'
, sched.schedule_id
, jobsched.job_id
, CASE
WHEN sched.freq_type = 1
THEN 'Once'
WHEN sched.freq_type = 4
AND sched.freq_interval = 1
THEN 'Daily'
WHEN sched.freq_type = 4
THEN 'Every ' + CAST(sched.freq_interval AS VARCHAR(5)) + ' days'
WHEN sched.freq_type = 8 THEN
REPLACE( REPLACE( REPLACE((
SELECT maskValue
FROM #weekDay AS x
WHERE sched.freq_interval & x.mask <> 0
ORDER BY mask FOR XML RAW)
, '"/><row maskValue="', ', '), '<row maskValue="', ''), '"/>', '')
+ CASE
WHEN sched.freq_recurrence_factor <> 0
AND sched.freq_recurrence_factor = 1
THEN '; weekly'
WHEN sched.freq_recurrence_factor <> 0
THEN '; every '
+ CAST(sched.freq_recurrence_factor AS VARCHAR(10)) + ' weeks' END
WHEN sched.freq_type = 16 THEN 'On day '
+ CAST(sched.freq_interval AS VARCHAR(10)) + ' of every '
+ CAST(sched.freq_recurrence_factor AS VARCHAR(10)) + ' months'
WHEN sched.freq_type = 32 THEN
CASE
WHEN sched.freq_relative_interval = 1 THEN 'First'
WHEN sched.freq_relative_interval = 2 THEN 'Second'
WHEN sched.freq_relative_interval = 4 THEN 'Third'
WHEN sched.freq_relative_interval = 8 THEN 'Fourth'
WHEN sched.freq_relative_interval = 16 THEN 'Last'
END +
CASE
WHEN sched.freq_interval = 1 THEN ' Sunday'
WHEN sched.freq_interval = 2 THEN ' Monday'
WHEN sched.freq_interval = 3 THEN ' Tuesday'
WHEN sched.freq_interval = 4 THEN ' Wednesday'
WHEN sched.freq_interval = 5 THEN ' Thursday'
WHEN sched.freq_interval = 6 THEN ' Friday'
WHEN sched.freq_interval = 7 THEN ' Saturday'
WHEN sched.freq_interval = 8 THEN ' Day'
WHEN sched.freq_interval = 9 THEN ' Weekday'
WHEN sched.freq_interval = 10 THEN ' Weekend'
END
+ CASE
WHEN sched.freq_recurrence_factor <> 0
AND sched.freq_recurrence_factor = 1
THEN '; monthly'
WHEN sched.freq_recurrence_factor <> 0
THEN '; every '
+ CAST(sched.freq_recurrence_factor AS VARCHAR(10)) + ' months'
END
WHEN sched.freq_type = 64 THEN 'StartUp'
WHEN sched.freq_type = 128 THEN 'Idle'
END AS 'frequency'
, ISNULL('Every ' + CAST(sched.freq_subday_interval AS VARCHAR(10)) +
CASE
WHEN sched.freq_subday_type = 2 THEN ' seconds'
WHEN sched.freq_subday_type = 4 THEN ' minutes'
WHEN sched.freq_subday_type = 8 THEN ' hours'
END, 'Once') AS 'subFrequency'
, REPLICATE('0', 6 - LEN(sched.active_start_time))
+ CAST(sched.active_start_time AS VARCHAR(6)) AS 'startTime'
, REPLICATE('0', 6 - LEN(sched.active_end_time))
+ CAST(sched.active_end_time AS VARCHAR(6)) AS 'endTime'
, REPLICATE('0', 6 - LEN(jobsched.next_run_time))
+ CAST(jobsched.next_run_time AS VARCHAR(6)) AS 'nextRunTime'
, CAST(jobsched.next_run_date AS CHAR(8)) AS 'nextRunDate'
FROM msdb.dbo.sysschedules AS sched
JOIN msdb.dbo.sysjobschedules AS jobsched
ON sched.schedule_id = jobsched.schedule_id
WHERE sched.enabled = 1
)
SELECT job.name AS [Job Name]
, CASE WHEN job.enabled = 1 THEN 'Enabled' ELSE 'Disabled' END AS [Job Status]
, COALESCE(sched.subFrequency, '') AS [Frequency]
, COALESCE(jh.last_duration, '') AS [Last Run Duration]
, COALESCE(jh.last_execution_start, '') AS [Last Run Time/Date]
FROM msdb.dbo.sysjobs AS job
LEFT JOIN myCTE AS sched
ON job.job_id = sched.job_id
LEFT JOIN #jobHistory AS jh
ON job.job_id = jh.job_id
WHERE jh.last_execution_start >= DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
AND job.name like '%MAINTENANCE - BACKUP%'
ORDER BY nextRunDate;
but although the results show the expected 'Failed' jobs, the 'Disabled' jobs are missing. I have also had help with this, as I have no SQL experience.
This Query has been created to check the Job History of roughtly 5/10 Backup Jobs within a 24 hour period, noting all the Failures (even if the last Run Succeeded). The seconds on the [Last Run Time/Date] also seem to be off, showing as soemthign like '50:00.0'
I also need a new column for the [Last Run Outcome] - to show if the Job 'Failed/Succeeded' as a Status.
Please let me know if you require any further information or a PasteBin of my code.

Return newest row when several columns are the same

I have a very complex Union query that returns up to two rows. If the second through the 15th columns are identical in both records, I want to return the results of the second record. Otherwise, return the results of the first record which is the newest record. The goal is to return the newest name and address with a pending flag only if the data is not the same.
SELECT TOP 1
1 AS updatePending,
a.entity_number,
a.name_title,
a.name_first,
a.name_middle,
a.name_last,
a.name_suffix,
LTRIM(RTRIM(REPLACE(
LTRIM(RTRIM(ISNULL(a.name_first, ''))) +
CASE WHEN LEN(LTRIM(RTRIM(ISNULL(a.name_first, '')))) = 1 THEN '. ' ELSE ' ' END +
LTRIM(RTRIM(ISNULL(a.name_middle, ''))) +
CASE WHEN LEN(LTRIM(RTRIM(ISNULL(a.name_middle, '')))) = 1 THEN '. ' ELSE ' ' END +
LTRIM(RTRIM(ISNULL(a.name_last, ''))) + ' ' +
LTRIM(RTRIM(ISNULL(a.name_suffix, '')))
,' ',' '))) AS name_full,
NULLIF(LTRIM(RTRIM(
LTRIM(RTRIM(ISNULL(a.company, ''))) +
LTRIM(RTRIM(ISNULL(a.firm_name, ''))))),'') AS company,
a.address1,
a.mailing_address,
a.city,
a.state,
a.zip_code AS zipcode,
a.internet_address AS email_address,
a.time_stamp
FROM statebar.dbo.STAGING_Address_Change_Request a
INNER JOIN Member m ON m.entity_number = a.entity_number
WHERE a.entity_number = (
SELECT m.entity_number
FROM Member m
INNER JOIN Named_Entity ne ON (ne.entity_number = m.entity_number)
WHERE ne.name_last = 'Park'
AND m.birth_year = '1958'
AND m.barno = '12345'
)
AND a.time_stamp > m.time_stamp
UNION ALL
SELECT TOP 1
0 AS updatePending,
ne.entity_number,
ne.name_title,
ne.name_first,
ne.name_middle,
ne.name_last,
ISNULL(ne.name_suffix, ''),
LTRIM(RTRIM(REPLACE(
LTRIM(RTRIM(ISNULL(ne.name_first, ''))) +
CASE WHEN LEN(LTRIM(RTRIM(ISNULL(ne.name_first, '')))) = 1 THEN '. ' ELSE ' ' END +
LTRIM(RTRIM(ISNULL(ne.name_middle, ''))) +
CASE WHEN LEN(LTRIM(RTRIM(ISNULL(ne.name_middle, '')))) = 1 THEN '. ' ELSE ' ' END +
LTRIM(RTRIM(ISNULL(ne.name_last, ''))) + ' ' +
LTRIM(RTRIM(ISNULL(ne.name_suffix, '')))
,' ',' '))) AS name_full,
NULLIF(LTRIM(RTRIM(
LTRIM(RTRIM(ISNULL(ne.company, ''))) +
LTRIM(RTRIM(ISNULL(ne.firm_name, ''))))),'') AS company,
ISNULL(ne.address1, ''),
ne.mailing_address,
ne.city,
ne.state,
ne.zip_code,
ne.internet_address AS email_address,
m.time_stamp
FROM Member m
INNER JOIN Named_Entity ne ON (ne.entity_number = m.entity_number)
LEFT JOIN statebar.dbo.STAGING_Address_Change_Request a ON a.entity_number = m.entity_number
WHERE ne.entity_number = (
SELECT m.entity_number
FROM Member m
INNER JOIN Named_Entity ne ON (ne.entity_number = m.entity_number)
WHERE ne.name_last = 'Park'
AND m.birth_year = '1958'
AND m.barno = '12345'
)
AND m.time_stamp > a.time_stamp
ORDER BY updatePending DESC, a.time_stamp DESC

How to get accumulated data using SUM, GROUP BY function

I beg your pardon for such a lengthy query, but I am in desperate need of help.
When I run the query below, I get daily data. But I want monthly data, using LASTDAY,
SUM, GROUP BY function.
For instance, if I pick '20130501' in #startDt# and '20130701' in #endDt#, it should give me 3 rows of accumulated results; May, June and July. Can anyone help?
SELECT X.*
FROM
(
SELECT
(CASE
WHEN DAY.DAY = 'SUM' THEN DAY.DAY
ELSE TO_CHAR (TO_DATE (DAY.DAY, 'YYYY-MM-DD'), 'YYYYMMDD')
END
) AS DAY,
DAY.WEEK,
MNOT.SUM_STD_CNT AS MNOT_CNT,
RSC.MOVIE_500K AS MOVIE_500K_CNT,
RSC.MOVIE_1M AS MOVIE_1M_CNT,
RSC.MOVIE AS MOVIE_CNT,
RSC.EXAM AS EXAM_CNT,
RSC.WEB AS WEB_CNT,
RSC.IMG AS IMG_CNT,
RSC.INTERRAC AS INTERRACTIVE_CNT,
RSC.DOC AS DOC_CNT,
MNOT.SUM_STD_CNT + RSC.MOVIE_500K + RSC.MOVIE_1M + RSC.MOVIE + RSC.EXAM + RSC.WEB + RSC.IMG + RSC.INTERRAC + RSC.DOC TOT_CNT
FROM
/* DATES */
(SELECT
TO_CHAR (TO_DATE (#startDt#,'YYYY-MM-DD')+LEVEL- 1, 'YYYYMMDD') AS DAY
FROM DUAL
CONNECT BY TO_DATE(#startDt#, 'YYYY-MM-DD') + LEVEL - 1 <![CDATA[<=]]> TO_DATE(#endDt#, 'YYYY-MM-DD')
UNION ALL
SELECT 'SUM', '' FROM DUAL
) DAY LEFT OUTER JOIN
/* RESOURCE */
(
SELECT
NVL(DT_G.COMM_DT, 'SUM') COMM_DT
,NVL(SUM(DT_G.MOVIE_500K), 0) AS MOVIE_500K
,NVL(SUM(DT_G.MOVIE_1M), 0) AS MOVIE_1M
,NVL(SUM(DT_G.MOVIE), 0) AS MOVIE
,NVL(SUM(DT_G.EXAM), 0) AS EXAM
,NVL(SUM(DT_G.DOC), 0) AS DOC
,NVL(SUM(DT_G.IMG), 0) AS IMG
,NVL(SUM(DT_G.WEB), 0) AS WEB
,NVL(SUM(DT_G.INTERRAC), 0) AS INTERRAC
FROM
(
SELECT
COMM_DT
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP10' THEN SUMT.SUM_500K END MOVIE_500K
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP10' THEN SUMT.SUM_1M END AS MOVIE_1M
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP10' THEN SUMT.SUM_500K+SUMT.SUM_1M END AS MOVIE
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP11' THEN SUMT.SUM_STD_CNT END AS EXAM
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP12' THEN SUMT.SUM_STD_CNT END AS DOC
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP13' THEN SUMT.SUM_STD_CNT END AS IMG
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP14' THEN SUMT.SUM_STD_CNT END AS WEB
, CASE SUMT.RSC_TP_DSCD WHEN 'RTP01' THEN SUMT.SUM_STD_CNT END AS INTERRAC
FROM (
SELECT RSC_TP_DSCD, SUM(STDY_CNT) AS SUM_STD_CNT, SUM(MOVIE_STDY_CNT_N1M) AS SUM_1M, SUM(MOVIE_STDY_CNT_N500K) AS SUM_500K, COMM_DT
FROM (
SELECT RSC_SNO, STDY_CNT, MOVIE_STDY_CNT_N1M, MOVIE_STDY_CNT_N500K, COMM_DT
FROM LRMS.V_EBSM_PKG_RSC_COMM_CNT
WHERE PKG_SNO = 0 AND RSC_SNO != 0
AND COMM_DT BETWEEN TO_CHAR(TO_DATE(#startDt#, 'YYYY-MM-DD'), 'YYYYMMDD') AND TO_CHAR(TO_DATE(#endDt#, 'YYYY-MM-DD'), 'YYYYMMDD')
) CNT
LEFT OUTER JOIN LRMS.V_LRRM_RSC RSC ON CNT.RSC_SNO = RSC.RSC_SNO
GROUP BY RSC_TP_DSCD, COMM_DT
) SUMT
) DT_G
GROUP BY ROLLUP(DT_G.COMM_DT)
) RSC ON DAY.DAY = RSC.COMM_DT
LEFT OUTER JOIN
(
SELECT NVL(SUM(STDY_CNT), 0) AS SUM_STD_CNT, NVL(COMM_DT, 'SUM') COMM_DT
FROM LRMS.V_EBSM_PKG_RSC_COMM_CNT
WHERE PKG_SNO != 0 AND RSC_SNO = 0
AND COMM_DT BETWEEN TO_CHAR(TO_DATE(#startDt#, 'YYYY-MM-DD'), 'YYYYMMDD') AND TO_CHAR(TO_DATE(#endDt#, 'YYYY-MM-DD'), 'YYYYMMDD')
GROUP BY ROLLUP(COMM_DT)
) MNOT ON DAY.DAY = MNOT.COMM_DT
) X
WHERE 1=1
and X.TOT_CNT IS NOT NULL
you can do something like
SELECT DATENAME(MONTH , DAY) , SUM(COLUMN1) , SUM(COLUMN2) ..
FROM (YOURQUERY) AS A
GROUP BY DATENAME(MONTH , DAY)
I think this will help you .

Query Runs Slower The Second Time

I have this massive query that I can typically run in under 2 minutes. However, when I run it a second time about a minute after, it goes on infinitely... so I kill the process and my SSMS session. I don't have any other jobs running in the background.
Is something else being retained on the server? I think I'm missing something as far as how SQL Server works.
Thanks.
EDIT: Here's the SQL (had to do a little obfuscation)
SELECT pl.OrangeLocationID ,
e.EventID ,
cr.Title AS [Event Type] ,
su.LastName + ', ' + su.FirstName AS FMR ,
CONVERT(VARCHAR(20), pl.Report_Date, 101) AS [Report Entry Date] ,
l.Name ,
l.Number ,
ll.SodaPopLocationID AS [SodaPop Location ID] ,
l.Zip ,
c.Channel ,
pl.DT AS [ReportedDate] ,
RIGHT(pl.DT_start, 8) AS [ReportedStartTime] ,
RIGHT(pl.DT_end, 8) AS [ReportedEndTime] ,
[CMS].dbo.dDateDiff(pl.DT_start, pl.DT_end) AS [ReportedDuration] ,
pl.scheduled_date AS [ScheduledDate] ,
RIGHT(pl.scheduled_start, 8) AS [ScheduledStartTime] ,
RIGHT(pl.scheduled_end, 8) AS [ScheduledEndTime] ,
[CMS].dbo.dDateDiff(pl.scheduled_start, pl.DT_end) AS [ScheduledDuration] ,
e.HoursPaid AS [Rep Hours Worked] ,
ISNULL(PP.[RepCount], 0) AS [RepCount] ,
CASE WHEN [CMS].dbo.dDateDiff(pl.DT_start, pl.DT_end) = ( e.HoursPaid / ISNULL(PP.[RepCount], 1) )
THEN [CMS].dbo.oa_HourDateDiff(pl.DT_start, pl.DT_end)
WHEN [CMS].dbo.dDateDiff(pl.scheduled_start, pl.DT_end) = ( e.HoursPaid / ISNULL(PP.[RepCount], 1) )
THEN [CMS].dbo.oa_HourDateDiff(pl.scheduled_start, pl.DT_end)
ELSE ( e.HoursPaid / ISNULL(PP.[RepCount], 1) )
END AS [FinalDuration] ,
g.[Description] AS [OA Market] ,
g.SodaPop_Region AS [SodaPop Region] ,
g.SodaPop_Area AS [SodaPop Area] ,
coup4 ,
coupo ,
coupo_e ,
card_num ,
promo ,
promo_no ,
promo_no_o ,
highlight1 ,
highlight2 ,
highlight3 ,
mgmt_reaction ,
mgmt_reaction_e ,
comm_p ,
comm_n ,
r.comments ,
s_fname ,
s_lname ,
v_title ,
ll.KeyAccountCorp AS [Key Account Corp.] ,
interact_new + interact_rep AS [interact_total] ,
samp_new + samp_rep AS [samp_total] ,
purch_new + purch_rep AS [purch_total] ,
23 / ( NULLIF(( interact_new + interact_rep ), 0) * 1.0 ) AS [Int_Crate] ,
CASE WHEN sampletype = 11 THEN ( purch_new + purch_rep ) / ( NULLIF(( samp_new + samp_rep ), 0) * 1.0 )
ELSE NULL
END AS [Samp_Crate] ,
coup1 + coup2 AS [coup_total] ,
CASE WHEN coup1 + coupo > 0 THEN 1
ELSE 0
END AS [CoupDist] ,
DATEPART(month, pl.DT) AS [Visit_Month] ,
DATEPART(quarter, pl.DT) AS [Quarter] ,
DATEPART(weekday, pl.DT) AS [Weekday] ,
CASE DATEPART(weekday, pl.DT)
WHEN 6 THEN 'Fri'
WHEN 7 THEN 'Sat'
WHEN 1 THEN 'Sun'
ELSE 'Mon-Thurs'
END AS [Weekday_Grouped] ,
CASE WHEN dbo.Exception(pl.OrangeLocationID, 12) = 1
OR dbo.Exception(pl.OrangeLocationID, 13) = 1
OR dbo.Exception(pl.OrangeLocationID, 14) = 1 THEN 1
ELSE 0
END AS [EVolume] ,
CASE WHEN dbo.DoesHaveException(pl.OrangeLocationID, 18) = 1 THEN 1
ELSE 0
END AS [CVolume] ,
CASE WHEN dbo.eException(pl.OrangeLocationID, 9) = 1
OR dbo.eException(pl.OrangeLocationID, 22) = 1 THEN 1
ELSE 0
END AS [Volumes] ,
CASE WHEN dbo.eException(pl.OrangeLocationID, 8) = 1
OR dbo.eException(pl.OrangeLocationID, 21) = 1 THEN 1
ELSE 0
END AS [Sales Price] ,
CASE WHEN dbo.eException(pl.OrangeLocationID, 11) = 1 THEN 1
ELSE 0
END AS [Sample Volume] ,
ISNULL(i.[NormalizedSold], 0) AS [EQBottlesSold] ,
CASE WHEN ISNULL(purch_new, 0) = 0 THEN 0
ELSE ISNULL(i.[NormalizedSold], 0) / ( purch_new + purch_rep )
END AS [EQBottlesSoldPerPurch] ,
ac.AvgSales ,
ac.STDEVSales ,
( ISNULL(i.[NormalizedSold], 0) - ac.AvgSales ) / ac.STDEVSales AS [sl] ,
ac.AvgPurchasers ,
ac.STDEVPurchasers ,
( ISNULL(r.purch_new, 0) - ac.AvgPurchasers ) / ac.STrchasers AS [ZScore_Purchasers] ,
ac.AvgConversions ,
ac.STDEVConversions ,
( ISNULL(( purch_new + purch_rep ) / ( NULLIF(( interact_new ), 0) ), 0) - ac.AvgConversions )
/ ac.STDEVConversions AS [ZScore_Conversions] ,
ac.[AvgSalesPerPurchaser] ,
ac.[STDEVSalesPerPurchaser] ,
( ISNULL(( CASE WHEN ISNULL(purch_new, 0) = 0 THEN 0
ELSE ISNULL(i.[NormalizedSold], 0) / ( purch_new + purch_rep )
END ), 0) - ac.[AvgSalesPerPurchaser] ) / ac.[STDEVSalesPerPurchaser] AS [SalesPerPurchaser] ,
( ( ( ISNULL(i.[NormalizedSold], 0) - ac.AvgSales ) / ac.STDEVSales )
+ ( (ISNULL(( CASE WHEN ISNULL(purch_new + purch_rep, 0) = 0 THEN 0
ELSE ISNULL(i.[NormalizedSold], 0) / ( purch_new + purch_rep )
END ), 0) - ac.[AvgSalesPerPurchaser]) ) ) / 4 AS [core] ,
( ( (( ISNULL(i.[NormalizedSold], 0) - ac.AvgSales ) / ac.STDEVSales) ) / 4 ) + 3 AS [core] ,
su.aaUserID ,
l.LsocationID
FROM [CMS_SodaPop].dbo.Schedule pl WITH ( NOLOCK )
INNER JOIN [CMS_SodaPop].dbo.Report r WITH ( NOLOCK ) ON r.OrangeLocationID = pl.OrangeLocationID
INNER JOIN [CMS].dbo.Users su WITH ( NOLOCK ) ON su.UserID = pl.Rep_FMR
INNER JOIN [CMS].dbo.Locations l WITH ( NOLOCK ) ON l.LocationID = pl.LocationID
INNER JOIN [CMS].dbo.OrangeReports cr WITH ( NOLOCK ) ON cr.RedID = pl.RedID
INNER JOIN [CMS_SodaPop].dbo.Events e WITH ( NOLOCK ) ON e.OrangeLocationID = pl.OrangeLocationID
INNER JOIN [CMS_SodaPop].dbo.MarketList g WITH ( NOLOCK ) ON g.GroupID = pl.GroupID
INNER JOIN [CMS_SodaPop].dbo.Locations ll WITH ( NOLOCK ) ON ll.LocationID = pl.LocationID
LEFT JOIN [CMS_SodaPop].dbo.Channels c WITH ( NOLOCK ) ON ll.ChannelID = c.ChannelID
LEFT JOIN ( SELECT PLocationID ,
COUNT(DISTINCT UserID) AS [RepCount]
FROM [CMS_roll].dbo.rollItems WITH ( NOLOCK )
WHERE RedID = 154
GROUP BY OrangeLocationID
) PP ON PP.OrangeLocationID = pl.OrangeLocationID
LEFT JOIN ( SELECT OrangeLocationID ,
SUM(NormalizedSold) AS [NormalizedSold]
FROM [Analysis].dbo.[vSodaPop_Retail_Inventory] WITH ( NOLOCK )
GROUP BY OrangeLocationID
) i ON i.OrangeLocationID = pl.OrangeLocationID
LEFT JOIN [Analysis].dbo.[vSodaPop_Calculations] ac WITH ( NOLOCK ) ON ac.[Quarter] = CASE WHEN DATEPART(MM,
[DT]) IN ( 10,
11, 12 ) THEN 4
END
AND ac.[Year] = DATEPART(YY, pl.DT)
WHERE pl.Activity = 1
AND pl.RedID = 154
AND pl.GroupID <> 444
AND pl.[DT] < GETDATE()
AND DATEPART(YY, [DT]) >= 2010
AND ISNULL(i.NormalizedSold, 0) >= 0
AND DATEPART(year, GETDATE()) = DATEPART(year, r.Insert_Date)
Would have to see the query to really dig in however..
you could try adding OPTION (RECOMPILE) to the end of the query to force it to create a new execution plan.
Are you using Temp Tables?
Cursors not deallocated & closed?
You can look at Profiler to see if anything looks different between the 2 executions.
Are you sure it isn't being blocked by another process the second time?
What happens if you execute
CHECKPOINT;
GO;
DBCC DROPCLEANBUFFERS;
GO;
DBCC FREEPROCCACHE;
GO;
between the queries? This is not really a solution but will help diagnosis.