SQL Pivot with Union All - sql

I'm using SQL Server 2012. I have 2 pivots (Current Year (CY) vs Last Year (LY) that work fine by themselves but want to Union them and have the results all togeather, how do I go about this? I need to have the data look like like this:
Cost Centre Name May_CY May_LY Jun_CY Jun LY.....This_Yr_Total Last_Yr_Total
This is my code:
SELECT
pvt.*,
Isnull(pvt.jan_CY, 0) +
Isnull(pvt.feb_CY, 0) +
Isnull(pvt.mar_CY, 0) +
Isnull(pvt.apr_CY, 0) +
Isnull(pvt.may_CY, 0) +
Isnull(pvt.jun_CY, 0) +
Isnull(pvt.jul_CY, 0) +
Isnull(pvt.aug_CY, 0) +
Isnull(pvt.sept_CY, 0) +
Isnull(pvt.oct_CY, 0) +
Isnull(pvt.nov_CY, 0) +
Isnull(pvt.Dec_CY, 0)
AS This_Year
FROM (SELECT [CostCentre], [CostCentreDesc] AS Name, { fn CONCAT(DATENAME(month, dbo.tblGLS215_2016_2017.AccDate), '_CY') } AS AccMonth, [RecordedAmount]
FROM [tblGLS215_2016_2017]
WHERE Employee <> '') AS s PIVOT (SUM([RecordedAmount]) FOR [AccMonth] IN (May_CY, Jun_CY, Jul_CY, Aug_CY, Sept_CY, Oct_CY, Nov_CY, Dec_CY, Jan_CY, Feb_CY, Mar_CY, Apr_CY)) AS pvt
UNION ALL
SELECT
pvt.*,
Isnull(pvt.jan_LY, 0) +
Isnull(pvt.feb_LY, 0) +
Isnull(pvt.mar_LY, 0) +
Isnull(pvt.apr_LY, 0) +
Isnull(pvt.may_LY, 0) +
Isnull(pvt.jun_LY, 0) +
Isnull(pvt.jul_LY, 0) +
Isnull(pvt.aug_LY, 0) +
Isnull(pvt.sept_LY, 0) +
Isnull(pvt.oct_LY, 0) +
Isnull(pvt.nov_LY, 0) +
Isnull(pvt.Dec_LY, 0)
AS Last_Year
FROM (SELECT [CostCentre], [CostCentreDesc] AS Name, { fn CONCAT(DATENAME(month, dbo.tblGLS215_2015_2016.AccDate), '_LY') } AS AccMonth, [RecordedAmount]
FROM [tblGLS215_2015_2016]
WHERE Employee <> '') AS s PIVOT (SUM([RecordedAmount]) FOR [AccMonth] IN (May_LY, Jun_LY, Jul_LY, Aug_LY, Sept_LY, Oct_LY, Nov_LY, Dec_LY, Jan_LY, Feb_LY, Mar_LY, Apr_LY)) AS pvt
Any help would be greatly appreciated.
This is one of the pivots for 'This Year' that returns results:
SELECT
pvt.*,
Isnull(
pvt.jan,0)+ Isnull(pvt.feb,0)+ Isnull(pvt.mar,0)+ Isnull(pvt.apr,0)+ Isnull(pvt.may,0)+ Isnull(pvt.jun,0)+ Isnull(pvt.jul,0)+
Isnull(pvt.aug,0)+ Isnull(pvt.sept,0)+ Isnull(pvt.oct,0)+ Isnull(pvt.nov,0) AS This_Year_Total
FROM
(
SELECT
[CostCentre],
[CostCentreDesc] AS Name,
CONVERT(
CHAR(4),
AccDate,
100
) AS [Month],
[RecordedAmount]
FROM
[tblGLS215_2016_2017]
) AS s PIVOT(
SUM( [RecordedAmount] ) FOR [Month] IN(
May,
Jun,
Jul,
Aug,
Sept,
Oct,
Nov,
DEC, Jan, Feb, Mar, Apr)) AS pvt

Select A.[CostCentre], A.Name
,A.[May_CY],B.[May_LY]
,A.[Jun_CY],B.[Jun_LY]
,A.[Jul_CY],B.[Jul_LY]
,A.[Aug_CY],B.[Aug_LY]
,A.[Sept_CY],B.[Sept_LY]
,A.[Oct_CY],B.[Oct_LY]
,A.[Nov_CY],B.[Nov_LY]
,A.[Dec_CY],B.[Dec_LY]
,A.[Jan_CY],B.[Jan_LY]
,A.[Feb_CY],B.[Feb_LY]
,A.[Mar_CY],B.[Mar_LY]
,A.[Apr_CY],B.[Apr_LY]
,A.[This_Year] as This_Yr_Total , B.[Last_Year] as Last_Yr_Total
From
(
SELECT
pvt.*,
Isnull(pvt.jan_CY, 0) +
Isnull(pvt.feb_CY, 0) +
Isnull(pvt.mar_CY, 0) +
Isnull(pvt.apr_CY, 0) +
Isnull(pvt.may_CY, 0) +
Isnull(pvt.jun_CY, 0) +
Isnull(pvt.jul_CY, 0) +
Isnull(pvt.aug_CY, 0) +
Isnull(pvt.sept_CY, 0) +
Isnull(pvt.oct_CY, 0) +
Isnull(pvt.nov_CY, 0) +
Isnull(pvt.Dec_CY, 0)
AS This_Year
FROM (SELECT [CostCentre], [CostCentreDesc] AS Name, { fn CONCAT(DATENAME(month, dbo.tblGLS215_2016_2017.AccDate), '_CY') } AS AccMonth, [RecordedAmount]
FROM [tblGLS215_2016_2017]
WHERE Employee <> '') AS s PIVOT (SUM([RecordedAmount]) FOR [AccMonth] IN (May_CY, Jun_CY, Jul_CY, Aug_CY, Sept_CY, Oct_CY, Nov_CY, Dec_CY, Jan_CY, Feb_CY, Mar_CY, Apr_CY)) AS pvt
)as A
full outer Join
(
SELECT
pvt.*,
Isnull(pvt.jan_LY, 0) +
Isnull(pvt.feb_LY, 0) +
Isnull(pvt.mar_LY, 0) +
Isnull(pvt.apr_LY, 0) +
Isnull(pvt.may_LY, 0) +
Isnull(pvt.jun_LY, 0) +
Isnull(pvt.jul_LY, 0) +
Isnull(pvt.aug_LY, 0) +
Isnull(pvt.sept_LY, 0) +
Isnull(pvt.oct_LY, 0) +
Isnull(pvt.nov_LY, 0) +
Isnull(pvt.Dec_LY, 0)
AS Last_Year
FROM (SELECT [CostCentre], [CostCentreDesc] AS Name, { fn CONCAT(DATENAME(month, dbo.tblGLS215_2015_2016.AccDate), '_LY') } AS AccMonth, [RecordedAmount]
FROM [tblGLS215_2015_2016]
WHERE Employee <> '') AS s PIVOT (SUM([RecordedAmount]) FOR [AccMonth] IN (May_LY, Jun_LY, Jul_LY, Aug_LY, Sept_LY, Oct_LY, Nov_LY, Dec_LY, Jan_LY, Feb_LY, Mar_LY, Apr_LY)) AS pvt
) as B
On A.[CostCentre]=B.[CostCentre] and A.Name=B.Name

Related

Conversion error when adding additional clauses

need your expertise on the "Conversion failed when converting date and/or time from character string". Much written about it and tried looking though it and understanding it to the extend I could but it did not solve the issue.
My code includes a number on conversations from dates and strings to the common numerical format. The conversation work separately form the main code and even together when the code is loose. However, when I start adding more conditions in the "where" function, SQL doesn't seem to like it. Do you possible know how to handle it best? Any help is much appreciated.
SELECT DISTINCT
DOTWHL as "DC",
DORELD as "Release date",
DODLDT as "Prelim ETA",
DOITNO as "Item #",
MMITDS as "Item name",
MMSTCN as "Lkr",
DOPPQT as "Plan Qty",
DOPPQT/MMCFI2 as "Plan Qty, pall",
DOPSTS as "Sts",
SUM(MHFOQT) as "FC between ETA & BBD",
MLSTQT as "Stock, LHU",
MMCFI2 as "LHU/PAL",
MMCFI3 as "LHU/Layer",
CASE WHEN DOPPQT >= MLSTQT
THEN CASE
WHEN MLSTQT > SUM(MHFOQT)
THEN 'YES'
ELSE 'NO'
END
ELSE CASE
WHEN DOPPQT > SUM(MHFOQT)
THEN 'YES'
ELSE 'NO'
END
END AS "FEFO violation necessary?",
CASE WHEN DOPPQT >= MLSTQT
THEN CASE
WHEN MLSTQT > SUM(MHFOQT)
THEN SUM(MHFOQT)
ELSE MLSTQT
END
ELSE CASE
WHEN DOPPQT > SUM(MHFOQT)
THEN SUM(MHFOQT)
ELSE DOPPQT
END
END AS "Recommended Qty, LHU",
CASE WHEN DOPPQT >= MLSTQT
THEN CASE
WHEN MLSTQT > SUM(MHFOQT)
THEN SUM(MHFOQT)/MMCFI2
ELSE MLSTQT/MMCFI2
END
ELSE CASE
WHEN DOPPQT > SUM(MHFOQT)
THEN SUM(MHFOQT)/MMCFI2
ELSE DOPPQT/MMCFI2
END
END AS "Recommended Qty, pall",
MLBREF as "Batch",
CASE WHEN MLSTQT > DOPPQT
THEN CASE
WHEN DOPPQT < SUM(MHFOQT)
THEN SUM(MHFOQT)-DOPPQT
ELSE NULL
END
ELSE NULL
END AS "Fill Up possibility, LHU",
Sales.Sold_Qty as "Sold Qty 10 weeks",
Sales.Forecasted_Qty as "FC Qty 10 weeks",
ISNULL(Sales.Sold_Qty/NULLIF(Sales.Forecasted_Qty,0), 0) as "Sold/FC, %",
MBBUYE as "NP",
MMRESP as "DmP",
CASE
WHEN Other_Assortments.item <> 0 THEN 'Many Markets'
ELSE 'DC 091 only'
END as "Distributed on"
FROM MVXJDTA.MDOPLP
LEFT JOIN MVXJDTA.MITMAS
ON DOCONO=MMCONO AND DOITNO=MMITNO
LEFT JOIN MVXJDTA.MITBAL
ON DOCONO=MBCONO AND DOFWHL=MBWHLO AND DOITNO=MBITNO
LEFT JOIN MVXJDTA.MITSTA
ON DOCONO=MHCONO AND DOTWHL=MHWHLO AND DOITNO=MHITNO
LEFT JOIN MVXJDTA.MITLOC
ON DOCONO=MLCONO AND DOFWHL=MLWHLO AND DOITNO=MLITNO
LEFT JOIN
(
SELECT DISTINCT
MHITNO as "Item_#",
sum(MHSOQT) as "Sold_Qty",
sum(MHFOQT) as "Forecasted_Qty"
FROM MVXJDTA.MITSTA
WHERE MHCONO=1
AND MHWHLO='091'
AND MHCYP6 between
(cast(datepart(yyyy, dateadd(ww,-10,getdate())) as varchar) + right('00' + cast(datepart(ww, dateadd(ww,-10,getdate())) as varchar),2)) and
(cast(datepart(yyyy, dateadd(ww,-1,getdate())) as varchar) + right('00' + cast(datepart(ww, dateadd(ww,-1,getdate())) as varchar),2))
AND right(MHCYP6, 2) <>'00'
group by MHITNO
)
as Sales
on DOITNO=Sales.Item_#
LEFT JOIN
(
select distinct
OIITNO as "item"
from MVXJDTA.OCUSMA
left join MVXJDTA.OASCUS
on OKCONO=OCCONO and OKCUNO=OCCUNO
left join MVXJDTA.OASITN
on OKCONO=OICONO and OCASCD=OIASCD
where OKCONO=1
and OITDAT='99999999'
and OKCSCD<>'KR'
and OKCSCD<>'HK'
and OKCSCD<>'TW'
and OKCSCD<>'SG'
and OKCSCD<>'MY'
and OKCSCD<>'TH'
and OKCSCD<>'PH'
group by OIITNO) as Other_Assortments
on Other_Assortments.item=DOITNO
WHERE DOCONO=1
AND DOTWHL='091'
AND DOFWHL='010'
AND MHCYP6 NOT IN (
SELECT
MHCYP6
FROM MVXJDTA.MITSTA
WHERE MHWHLO='091'
AND MHCONO=1
AND RIGHT(CONVERT(VARCHAR, MHCYP6, 102), 2) ='00'
)
AND MHCYP6 BETWEEN
CASE
WHEN DATEPART(WEEK, CONVERT(DATETIME, RIGHT(DODLDT, 2) + '/' + LEFT(RIGHT(DODLDT, 4), 2) + '/' + LEFT (DODLDT, 4), 103))<10
THEN CONCAT( DATEPART(YEAR, CONVERT(DATETIME, RIGHT(DODLDT, 2) + '/' + LEFT(RIGHT(DODLDT, 4), 2) + '/' + LEFT (DODLDT, 4), 103)), 0,
DATEPART(WEEK, CONVERT(DATETIME, RIGHT(DODLDT, 2) + '/' + LEFT(RIGHT(DODLDT, 4), 2) + '/' + LEFT (DODLDT, 4), 103)))
ELSE CONCAT( DATEPART(YEAR, CONVERT(DATETIME, RIGHT(DODLDT, 2) + '/' + LEFT(RIGHT(DODLDT, 4), 2) + '/' + LEFT (DODLDT, 4), 103)),
DATEPART(WEEK, CONVERT(DATETIME, RIGHT(DODLDT, 2) + '/' + LEFT(RIGHT(DODLDT, 4), 2) + '/' + LEFT (DODLDT, 4), 103)))
END
CASE
WHEN MLBREF IS NULL
THEN '999999'
ELSE CASE
WHEN DATEPART(WEEK, DATEADD(DAY, -82, CONVERT(DATETIME, RIGHT(MLBREF, 2) + '/' + LEFT(RIGHT(MLBREF, 4), 2) + '/' + '20'+LEFT (MLBREF, 2), 103)))<10
THEN CONCAT(DATEPART(YEAR, DATEADD(DAY, -82, CONVERT(DATETIME, RIGHT(MLBREF, 2) + '/' + LEFT(RIGHT(MLBREF, 4), 2) + '/' + '20'+LEFT (MLBREF, 2), 103))), 0,
DATEPART(WEEK, DATEADD(DAY, -82, CONVERT(DATETIME, RIGHT(MLBREF, 2) + '/' + LEFT(RIGHT(MLBREF, 4), 2) + '/' + '20'+LEFT (MLBREF, 2), 103))))
ELSE CONCAT(DATEPART(YEAR, DATEADD(DAY, -82, CONVERT(DATETIME, RIGHT(MLBREF, 2) + '/' + LEFT(RIGHT(MLBREF, 4), 2) + '/' + '20'+LEFT (MLBREF, 2), 103))),
DATEPART(WEEK, DATEADD(DAY, -82, CONVERT(DATETIME, RIGHT(MLBREF, 2) + '/' + LEFT(RIGHT(MLBREF, 4), 2) + '/' + '20'+LEFT (MLBREF, 2), 103))))
END
END
AND (MLSTQT-MLALQT)<>0
GROUP BY DOTWHL, DORELD, MLBREF, DODLDT, DOITNO, DOPPQT, MLSTQT, MMITDS, MLALQT, MBPLCD, MMSTCN, MMCFI2, MMCFI3, DOPSTS, Sales.Sold_Qty, Sales.Forecasted_Qty, MBBUYE, MMRESP, Other_Assortments.item
ORDER BY DOTWHL, DORELD

Merge query in SQL Server stored procedure

I'll admit I don't have a lot of DB experience as my last job had a DBA but this place has none. I have an existing MASSIVE stored procedure that I need to modify (I noticed a lot of duplication and cut that out).
Right now, it pulls so much data they used a cache table or the page crashes. They just want a smaller amount of data now for a separate page. I'm trying to edit this stored procedure and merge in my new query to it.
The existing stored procedure:
ALTER PROCEDURE [dbo].[PurchasingSupplyChainNeeds]
(#maxAgeInHours INT = 24)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sqlStmt NVARCHAR(max)
DECLARE #myName NVARCHAR(max) = Object_name(##PROCID)
DECLARE #needsRefresh INT
EXEC #needsRefresh = [cache].[NeedsRefresh]
#myName,
#maxAgeInHours
IF #needsRefresh = 1
BEGIN
DECLARE #CurrentMonth INT
DECLARE #DayOfWeek INT
DECLARE #EndOfWeekDate DATETIME
DECLARE #StartOfNextWeek DATETIME
DECLARE #WorkDaysInMonth INT
DECLARE #RunningDate DATE
DECLARE #WorkDaysLeftInMonth INT
DECLARE #DayOffset INT
SELECT #CurrentMonth = DATEPART(MONTH, GETDATE())
SELECT #DayOfWeek = DATEPART(WEEKDAY, GETDATE())
IF (#DayOfWeek = 1)
BEGIN
SET #StartOfNextWeek = GETDATE()
END
ELSE
BEGIN
SET #StartOfNextWeek = DATEADD(day, 8 - #DayOfWeek, GETDATE())
END
SELECT #DayOfWeek = DATEPART(weekday, GETDATE())
IF (#DayOfWeek = 7)
BEGIN
SET #EndOfWeekDate = Getdate()
END
ELSE
BEGIN
SET #EndOfWeekDate = DATEADD(day, -#DayOfWeek, GETDATE())
END
SET #WorkDaysInMonth = 0
SET #RunningDate = CONVERT(DATE, CONVERT(VARCHAR, #CurrentMonth) + '/1/' + CONVERT(VARCHAR, Datepart(year, Getdate())))
WHILE ( Datepart(month, #RunningDate) = #CurrentMonth )
BEGIN
SET #DayOfWeek = Datepart(weekday, #RunningDate)
IF ( #DayOfWeek != 1
AND #DayOfWeek != 7 )
BEGIN
SET #WorkDaysInMonth = #WorkDaysInMonth + 1
END
SET #RunningDate = Dateadd(day, 1, #RunningDate)
END
SET #WorkDaysLeftInMonth = 0
SET #DayOffset = 0
WHILE ( Datepart(month, Dateadd(day, #DayOffset, Getdate())) = #CurrentMonth )
BEGIN
SET #DayOfWeek = Datepart(weekday, Dateadd(day, #DayOffset, Getdate()))
IF ( #DayOfWeek != 1
AND #DayOfWeek != 7 )
BEGIN
SET #WorkDaysLeftInMonth = #WorkDaysLeftInMonth + 1
END
SET #DayOffset = #DayOffset + 1
END;
WITH j
AS (SELECT Rtrim(Ltrim(imitmidx_sql.item_no)) AS ItemNo,
Rtrim(Ltrim(ISNULL(imitmidx_sql.item_desc_1, ''))) AS ItemDescription1,
Rtrim(Ltrim(ISNULL(imitmidx_sql.item_desc_2, ''))) AS ItemDescription2,
Rtrim(Ltrim(ISNULL(imitmidx_sql.activity_cd, '-'))) AS ActivityCode,
Rtrim(Ltrim(imitmidx_sql.pur_or_mfg)) AS PurchasedOrMfg,
Rtrim(Ltrim(ISNULL(imitmidx_sql.uom, '-'))) AS UOM,
/*
case statements ensure the price, avg_cost & price
are only observed from the item's primary location;
not secondary locations such as Amazon warehouses
*/
CASE
WHEN iminvloc_sql.loc = imitmidx_sql.loc THEN Rtrim(Ltrim(ISNULL(cicmpy.cmp_name, '')))
ELSE ''
END AS VendorName,
CASE
WHEN iminvloc_sql.loc = imitmidx_sql.loc THEN iminvloc_sql.avg_cost
ELSE 0
END AS AverageCost,
CASE
WHEN iminvloc_sql.loc = imitmidx_sql.loc THEN iminvloc_sql.price
ELSE 0
END AS Price,
iminvloc_sql.qty_on_hand AS QtyOnHand,
iminvloc_sql.qty_allocated AS QtyAllocated,
(SELECT ISNULL(qty_on_hand, 0)
FROM iminvloc_sql WITH (NOLOCK)
WHERE item_no = imitmidx_sql.item_no
AND loc = '3IV') AS QtyIn3IV,
(SELECT ISNULL(qty_on_hand, 0)
FROM iminvloc_sql WITH (NOLOCK)
WHERE item_no = imitmidx_sql.item_no
AND loc = '3TI') AS QtyIn3TI,
(SELECT ISNULL(qty_on_hand, 0)
FROM iminvloc_sql WITH (NOLOCK)
WHERE item_no = imitmidx_sql.item_no
AND loc = '3FA') AS QtyIn3FA,
(SELECT ISNULL(Sum(qty_ordered), 0)
FROM (SELECT y.qty_ordered
FROM oeordhdr_sql x WITH (NOLOCK)
INNER JOIN oeordlin_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE x.ord_type = 'O'
AND x.entered_dt BETWEEN Dateadd(day, 1, Dateadd(week, -52, Cast(#EndOfWeekDate AS DATE))) AND Dateadd(week, -51, Cast(#EndOfWeekDate AS DATE))
AND y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc
AND x.status != 'L'
UNION ALL
SELECT y.qty_to_ship
FROM (SELECT DISTINCT ord_type,
ord_no,
entered_dt
FROM oehdrhst_sql WITH (NOLOCK)
WHERE ord_type = 'O'
AND entered_dt BETWEEN Dateadd(day, 1, Dateadd(week, -52, Cast(#EndOfWeekDate AS DATE))) AND Dateadd(week, -51, Cast(#EndOfWeekDate AS DATE))) x
INNER JOIN oelinhst_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc) s) AS SalesWeek1,
---Sales week 2 to 51 here
(SELECT ISNULL(Sum(qty_ordered), 0)
FROM (SELECT y.qty_ordered
FROM oeordhdr_sql x WITH (NOLOCK)
INNER JOIN oeordlin_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE x.ord_type = 'O'
AND x.entered_dt BETWEEN Dateadd(day, 1, Dateadd(week, -1, Cast(#EndOfWeekDate AS DATE))) AND #EndOfWeekDate
AND y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc
AND x.status != 'L'
UNION ALL
SELECT y.qty_to_ship
FROM (SELECT DISTINCT ord_type,
ord_no,
entered_dt
FROM oehdrhst_sql WITH (NOLOCK)
WHERE ord_type = 'O'
AND entered_dt BETWEEN Dateadd(day, 1, Dateadd(week, -1, Cast(#EndOfWeekDate AS DATE))) AND #EndOfWeekDate) x
INNER JOIN oelinhst_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc) s) AS SalesWeek52,
(SELECT ISNULL(Sum(qty_ordered), 0)
FROM (SELECT y.qty_ordered
FROM oeordhdr_sql x WITH (NOLOCK)
INNER JOIN oeordlin_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE x.ord_type = 'O'
AND x.entered_dt BETWEEN Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Dateadd(year, -2, Getdate()))) AS DATE) AND Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Dateadd(year, -1, Getdate()))) AS DATE)
AND y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc
AND x.status != 'L'
UNION ALL
SELECT y.qty_to_ship
FROM (SELECT DISTINCT ord_type,
ord_no,
entered_dt
FROM oehdrhst_sql WITH (NOLOCK)
WHERE ord_type = 'O'
AND entered_dt BETWEEN Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Dateadd(year, -2, Getdate()))) AS DATE) AND Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Dateadd(year, -1, Getdate()))) AS DATE)) x
INNER JOIN oelinhst_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc) s) AS SalesYear1,
(SELECT ISNULL(Sum(qty_ordered), 0)
FROM (SELECT y.qty_ordered
FROM oeordhdr_sql x WITH (NOLOCK)
INNER JOIN oeordlin_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE x.ord_type = 'O'
AND x.entered_dt BETWEEN Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Dateadd(year, -1, Getdate()))) AS DATE) AND Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Getdate())) AS DATE)
AND y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc
AND x.status != 'L'
UNION ALL
SELECT y.qty_to_ship
FROM (SELECT DISTINCT ord_type,
ord_no,
entered_dt
FROM oehdrhst_sql WITH (NOLOCK)
WHERE ord_type = 'O'
AND entered_dt BETWEEN Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Dateadd(year, -1, Getdate()))) AS DATE) AND Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Getdate())) AS DATE)) x
INNER JOIN oelinhst_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc) s) AS SalesYear2,
(SELECT ISNULL(Sum(qty_ordered), 0)
FROM (SELECT y.qty_ordered
FROM oeordhdr_sql x WITH (NOLOCK)
INNER JOIN oeordlin_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE x.ord_type = 'O'
AND x.entered_dt BETWEEN Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Getdate())) AS DATE) AND Cast(Getdate() AS DATE)
AND y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc
AND x.status != 'L'
UNION ALL
SELECT y.qty_to_ship
FROM (SELECT DISTINCT ord_type,
ord_no,
entered_dt
FROM oehdrhst_sql WITH (NOLOCK)
WHERE ord_type = 'O'
AND entered_dt BETWEEN Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Getdate())) AS DATE) AND Cast(Getdate() AS DATE)) x
INNER JOIN oelinhst_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc) s) AS SalesYTD,
CASE
WHEN Datediff(week, imitmidx_sql.activity_dt, Getdate()) > 52 THEN 52
ELSE Datediff(week, imitmidx_sql.activity_dt, Getdate())
END AS ActiveWeeks,
(SELECT ( ISNULL(ForecastQty, 0) / #WorkDaysInMonth ) * #WorkDaysLeftInMonth
FROM HP_PurchasingForecast
WHERE ItemNo = imitmidx_sql.item_no
AND [Month] = Datepart(month, Getdate())
AND [Year] = Datepart(year, Getdate())
AND Active = 1) AS RemainingForecastQty,
(SELECT ISNULL(ForecastQty, 0)
FROM HP_PurchasingForecast
WHERE ItemNo = imitmidx_sql.item_no
AND [Month] = Datepart(month, Getdate())
AND [Year] = Datepart(year, Getdate())
AND Active = 1) AS ForecastQty1,
---ForecastQty 2 to 11
(SELECT ISNULL(ForecastQty, 0)
FROM HP_PurchasingForecast
WHERE ItemNo = imitmidx_sql.item_no
AND [Month] = Datepart(month, Dateadd(month, 11, Getdate()))
AND [Year] = Datepart(year, Dateadd(month, 11, Getdate()))
AND Active = 1) AS ForecastQty12,
( (SELECT ISNULL(Sum(CASE
WHEN receipt_dt IS NULL THEN qty_ordered
ELSE qty_remaining
END), 0)
FROM poordlin_sql WITH (NOLOCK)
WHERE ord_status IN ( 'P', 'R' )
AND item_no = imitmidx_sql.item_no
AND promise_dt IS NOT NULL
AND promise_dt <= CONVERT(DATE, Dateadd(day, 6, #StartOfNextWeek))
AND
(
receipt_dt IS NULL
OR ISNULL(qty_remaining, 0) > 0
)
)
+ (SELECT ISNULL(Sum(y.quantity), 0)
FROM imtrnhdr_sql x WITH (NOLOCK)
INNER JOIN imtrndtl_sql y WITH (NOLOCK)
ON x.transit_no = y.transit_no
WHERE x.status IN ( 'A', 'S' )
AND y.item_no = imitmidx_sql.item_no
AND x.to_loc = iminvloc_sql.loc
AND x.due_date <= CONVERT(DATE, Dateadd(day, 6, #StartOfNextWeek))
AND NOT
(
x.from_loc = '3IV'
AND x.temp_loc = '3TI'
AND x.to_loc = iminvloc_sql.loc
)
) ) AS POQty1,
---POQty 2 to 52
( (SELECT ISNULL(Sum(CASE
WHEN receipt_dt IS NULL THEN qty_ordered
ELSE qty_remaining
END), 0)
FROM poordlin_sql WITH (NOLOCK)
WHERE ord_status IN ( 'P', 'R' )
AND item_no = imitmidx_sql.item_no
AND promise_dt IS NOT NULL
AND promise_dt BETWEEN CONVERT(DATE, Dateadd(day, 357, #StartOfNextWeek)) AND CONVERT(DATE, Dateadd(day, 363, #StartOfNextWeek))
AND
(
receipt_dt IS NULL
OR ISNULL(qty_remaining, 0) > 0
)
)
+ (SELECT ISNULL(Sum(y.quantity), 0)
FROM imtrnhdr_sql x WITH (NOLOCK)
INNER JOIN imtrndtl_sql y WITH (NOLOCK)
ON x.transit_no = y.transit_no
WHERE x.status IN ( 'A', 'S' )
AND y.item_no = imitmidx_sql.item_no
AND x.to_loc = iminvloc_sql.loc
AND x.due_date BETWEEN CONVERT(DATE, Dateadd(day, 357, #StartOfNextWeek)) AND CONVERT(DATE, Dateadd(day, 363, #StartOfNextWeek))
AND NOT
(
x.from_loc = '3IV'
AND x.temp_loc = '3TI'
AND x.to_loc = iminvloc_sql.loc
)
) ) AS POQty52
FROM imitmidx_sql imitmidx_sql WITH (NOLOCK)
LEFT OUTER JOIN iminvloc_sql iminvloc_sql WITH (NOLOCK)
ON imitmidx_sql.item_no = iminvloc_sql.item_no
AND
(
imitmidx_sql.loc = iminvloc_sql.loc /* Primary location for the item */
OR iminvloc_sql.loc = '3FA'/*Amazon Fullfillment Center*/
)
LEFT OUTER JOIN cicmpy cicmpy
ON iminvloc_sql.vend_no = cicmpy.cmp_code
AND cicmpy.cmp_type = 'S'),
i
AS (SELECT [ItemNo],
[ItemDescription1],
[ItemDescription2],
[ActivityCode],
[PurchasedOrMfg],
[UOM],
Max([VendorName]) [VendorName],
Max([AverageCost]) [AverageCost],
Max([Price]) [Price],
Sum([QtyOnHand]) [QtyOnHand],
Sum([QtyAllocated]) [QtyAllocated],
Max([QtyIn3IV]) [QtyIn3IV],
Max([QtyIn3TI]) [QtyIn3TI],
Max([QtyIn3FA]) [QtyIn3FA],
Sum([SalesWeek1]) [SalesWeek1],
---SalesWeek2 to 51
Sum([SalesWeek52]) [SalesWeek52],
Sum([SalesYear1]) [SalesYear1],
Sum([SalesYear2]) [SalesYear2],
Sum([SalesYTD]) [SalesYTD],
Avg([ActiveWeeks]) [ActiveWeeks],
Avg([RemainingForecastQty]) [RemainingForecastQty],
Avg([ForecastQty1]) [ForecastQty1],
---ForecastQty2 to 11
Avg([ForecastQty12]) [ForecastQty12],
Avg([POQty1]) [POQty1],
---POQty2 to 51
Avg([POQty52]) [POQty52]
FROM j
WHERE [PurchasedOrMfg] = 'M'
GROUP BY [ItemNo],
[ItemDescription1],
[ItemDescription2],
[ActivityCode],
[PurchasedOrMfg],
[UOM])
SELECT i.*,
CASE i.ActiveWeeks
WHEN 0 THEN 0
ELSE ( i.SalesWeek52 + i.SalesWeek51 + i.SalesWeek50 + i.SalesWeek49 + i.SalesWeek48 + i.SalesWeek47 ) /
(
CASE
WHEN i.ActiveWeeks < 6 THEN i.ActiveWeeks
ELSE 6
END
)
END AS Last6WeeksAvg,
CASE i.ActiveWeeks
WHEN 0 THEN 0
ELSE ( i.SalesWeek52 + i.SalesWeek51 + i.SalesWeek50 + i.SalesWeek49 + i.SalesWeek48 + i.SalesWeek47 + i.SalesWeek46 + i.SalesWeek45 + i.SalesWeek44 + i.SalesWeek43 + i.SalesWeek42 + i.SalesWeek41 ) /
(
CASE
WHEN i.ActiveWeeks < 12 THEN i.ActiveWeeks
ELSE 12
END
)
END AS Last12WeeksAvg,
CASE i.ActiveWeeks
WHEN 0 THEN 0
ELSE ( i.SalesWeek52 + i.SalesWeek51 + i.SalesWeek50 + i.SalesWeek49 + i.SalesWeek48 + i.SalesWeek47 + i.SalesWeek46 + i.SalesWeek45 + i.SalesWeek44 + i.SalesWeek43 + i.SalesWeek42 + i.SalesWeek41 + i.SalesWeek40 + i.SalesWeek39 + i.SalesWeek38 + i.SalesWeek37 + i.SalesWeek36 + i.SalesWeek35 + i.SalesWeek34 + i.SalesWeek33 + i.SalesWeek32 + i.SalesWeek31 + i.SalesWeek30 + i.SalesWeek29 + i.SalesWeek28 + i.SalesWeek27 + i.SalesWeek26 + i.SalesWeek25 + i.SalesWeek24 + i.SalesWeek23 + i.SalesWeek22 + i.SalesWeek21 + i.SalesWeek20 + i.SalesWeek19 + i.SalesWeek18 + i.SalesWeek17 + i.SalesWeek16 + i.SalesWeek15 + i.SalesWeek14 + i.SalesWeek13 + i.SalesWeek12 + i.SalesWeek11 + i.SalesWeek10 + i.SalesWeek9 + i.SalesWeek8 + i.SalesWeek7 + i.SalesWeek6 + i.SalesWeek5 + i.SalesWeek4 + i.SalesWeek3 + i.SalesWeek2 + i.SalesWeek1 ) / i.ActiveWeeks
END AS Last52WeeksAvg,
( ISNULL(i.RemainingForecastQty, 0) + ISNULL(i.ForecastQty2, 0) + ISNULL(i.ForecastQty3, 0) + ISNULL(i.ForecastQty4, 0) + ISNULL(i.ForecastQty5, 0) + ISNULL(i.ForecastQty6, 0) + ISNULL(i.ForecastQty7, 0) + ISNULL(i.ForecastQty8, 0) + ISNULL(i.ForecastQty9, 0) + ISNULL(i.ForecastQty10, 0) + ISNULL(i.ForecastQty11, 0) + ISNULL(i.ForecastQty12, 0) ) / 52 AS AvgWeeklyForecast,
ISNULL(i.QtyIn3FA, 0) + ISNULL(i.QtyOnHand, 0) + ISNULL(i.QtyIn3TI, 0) - ISNULL(i.QtyAllocated, 0) AS QtyAvailable
INTO #outputToCache
FROM i
SET #sqlStmt = 'select * INTO [cache].[' + #myName + '] from #outputToCache'
EXEC sp_executesql
#sqlStmt
END
SET #sqlStmt = 'select * from [cache].[' + #myName + ']'
EXEC sp_executesql
#sqlStmt
END
My query:
SELECT
tb_1.SubPart AS 'Sub Part',
SUM(tb_1.FinalItemSubPartQuantity) 'Sub Part Quantity Needed',
SUM(tb_1.FinalItemSubPartQuantity * tb_2.SalesWeek1) 'Total Sales Week 1',
--- Total Sales Week 2 to 51 here
SUM(tb_1.FinalItemSubPartQuantity * tb_2.SalesWeek52) 'Total Sales Week 52'
FROM
[009Reports].[dbo].[ANC Parts] tb_1
JOIN
[555].[cache].[PurchasingSupplyChainNeeds] tb_2 ON tb_1.FinalPartNo = tb_2.ItemNo
GROUP BY
tb_1.SubPart
Replacing this query below with mine:
AS (SELECT [ItemNo],
[ItemDescription1],
[ItemDescription2],
This is the error I get:
Msg 208, Level 16, State 1, Line 3168
Invalid object name 'i'
My query has 2 different tables in 2 different databases.
Currently, the stored procedure is using CTEs to create "temporary tables" based on (ugly and monstruous) queries and then use them to fill a table.
In general terms, a CTE is a table made from the results of a query, that's only usable by the immediate next query (this is: you create a CTE, then use it on a SELECT, INSERT, UPDATE... then the CTE gets destroyed).
What the SP is doing is this:
Creates CTE j using info and calculations from certain tables
Uses info from CTE j to create CTE i
Uses info from CTE i to create a temporary table #outputToCache
Dumps info from #outputToCache into a physical table cache.PurchasingSupplyChainNeeds
SELECTs and returns the info from cache.PurchasingSupplyChainNeeds as the resultset from the stored procedure
The error you're getting is because you're replacing the creation of CTE i with your own query, but i is still used later on to fill the temporary table.
Now, you say that what you are trying to achieve, is to retrieve a smaller amount of data from this last "cache" table for a separate page. IF I UNDERSTAND CORRECTLY (emphasized because I'm not 100% sure I got it already) you shouldn't modify this stored procedure (this is, add your query into it) because that would change the output of it, and would break anything that uses it. Not only that, your query is using info from the cache table, but the part you're trying to replace is what creates the CTE i that ultimately fills such table.
If what you really want to do is to change the resultset returned from this SP, then the query you need to replace with your own is the one that's assigned to the #sqlStmt variable at the end, so instead of
SET #sqlStmt = 'select * from [cache].[' + #myName + ']'
you would have
SET #sqlStmt = 'SELECT tb_1.SubPart AS [Sub Part], SUM(tb_1.FinalItemSubPartQuantity) [Sub Part Quantity Needed], SUM(tb_1.FinalItemSubPartQuantity * tb_2.SalesWeek1) [Total Sales Week 1],...'
*Note the change of quoted aliases to square-bracketed ones
If your query is meant to return information for a separate page, you should create another stored procedure with your query and then call this new SP from this separate page. This is of course if this cache table doesn't get emptied/deleted by a different process later on. If this is the case, then you're into a world of pain, as you would either need to duplicate this existing SP almost in its entirety into your new SP and change the output as stated above; add an optional parameter that determines wich output should this SP return (e.g. if the parameter is 1 the output is the same as now, but if the parameter is 2 the output is your query); or change this existing stored procedure to not return a value and make other(s) to calls this one and return information as needed. Probably the last option is the "least ugly" one.

How to get per hour in data set?

I'm trying to get data per hour however as I execute, the data for day is displayed in the table. IDC_YMD with per hour result must be in the table and I'm not sure if I have the right SUBSTR(string, start, length).
SELECT EQP_ID, EQP_NAME, 'WorkPreparation' GUBUN,WorkPreparation
CNT,SITE_CODE,GODS_CODE,STEP_NAME,IDC_YMD,IDC_SUMR_UNIT_CODE,MTBI,MTBA
FROM
(
SELECT CASE WHEN WorkPreparation = 0 THEN '-' ELSE EQP_ID END AS EQP_ID, CASE WHEN WorkPreparation =
0 THEN '-' ELSE SUBSTR(EQP_NAME,1,4) END AS EQP_NAME,
WorkPreparation,SITE_CODE,GODS_CODE,STEP_NAME,IDC_YMD,IDC_SUMR_UNIT_CODE,MTBI,MTBA
FROM(
SELECT EQP_ID, EVENT_COMMENT EQP_NAME, SUM(WORK_PRE_CNT) WorkPreparation, A.SITE_CODE
, A.GODS_CODE
, A.EES_STEP_ID AS STEP_NAME
, TO_CHAR(TO_NUMBER(SUBSTR(A.IDC_YMD, 12, 2))) || '/' || TO_CHAR(TO_NUMBER(SUBSTR(A.IDC_YMD, 12,
2))) AS IDC_YMD
, 'D' AS IDC_SUMR_UNIT_CODE
, CASE WHEN (SUM(NVL(A.INTR_CNT, 0)) + SUM(NVL(A.BRDN_CNT, 0))) = 0
THEN ROUND(SUM(NVL(A.OPER_MOP, 0)),1)
ELSE ROUND(SUM(NVL(A.OPER_MOP, 0)) / (SUM(NVL(A.INTR_CNT, 0)) + SUM(NVL(A.BRDN_CNT, 0))) /
60,1)
END AS MTBI
, CASE WHEN (SUM(NVL(A.INTR_CNT, 0)) + SUM(NVL(A.BRDN_CNT, 0)) + SUM(NVL(A.WORK_PRE_CNT, 0)) +
SUM(NVL(A.PROD_CHANGE_CNT, 0)) + SUM(NVL(A.QUAL_EXATN_CNT, 0)) +
SUM(NVL(A.MTR_EXATN_CNT, 0)) + SUM(NVL(A.STEP_CHRC_LOSS_CNT, 0)) +
SUM(NVL(A.IDLE_3MN_UND_EXCPT_CNT, 0))) = 0
THEN 0
ELSE ROUND(SUM(NVL(A.OPER_MOP, 0)) / (SUM(NVL(A.INTR_CNT, 0)) + SUM(NVL(A.BRDN_CNT, 0)) +
SUM(NVL(A.WORK_PRE_CNT, 0)) + SUM(NVL(A.PROD_CHANGE_CNT, 0)) + SUM(NVL(A.QUAL_EXATN_CNT, 0)) +
SUM(NVL(A.MTR_EXATN_CNT, 0)) + SUM(NVL(A.STEP_CHRC_LOSS_CNT,
0)) + SUM(NVL(A.IDLE_3MN_UND_EXCPT_CNT, 0))) / 60,1)
END AS MTBA
FROM IFR_EES_PCL A
WHERE SITE_CODE = 'E502AA'
AND GODS_CODE = 'N5210'
AND MTBI_MNG_YN = 'Y'
AND EES_STEP_ID = 'TP'
AND A.IDC_YMD BETWEEN TO_CHAR(SYSDATE-6, 'YYYYMMDDHH') AND TO_CHAR(SYSDATE, 'YYYYMMDD')
GROUP BY EQP_ID, EVENT_COMMENT,A.SITE_CODE
, A.GODS_CODE
,A.EQP_TYPE
, A.EES_STEP_ID
, TO_CHAR(TO_NUMBER(SUBSTR(A.IDC_YMD, 12, 2)))
, A.IDC_YMD
ORDER BY A.IDC_YMD, MTBI DESC--TO_CHAR(TO_NUMBER(SUBSTR(A.IDC_YMD, 12, 2)))
))
WHERE ROWNUM <= 10
and EQP_NAME like 'TA%'
Thank you!

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 Server Pivot Before Current month

I'm using SQL Server 2012 and have the below that forms part of a much larger statement to calculate the total of each month in a field called 'This_Year'. This works fine:
SELECT
pvt.*,
Isnull(pvt.jan_CY, 0) + Isnull(pvt.feb_CY, 0) +
Isnull(pvt.mar_CY, 0) + Isnull(pvt.apr_CY, 0) +
Isnull(pvt.may_CY, 0) + Isnull(pvt.jun_CY, 0) +
Isnull(pvt.jul_CY, 0) + Isnull(pvt.aug_CY, 0) +
Isnull(pvt.sep_CY, 0) + Isnull(pvt.oct_CY, 0) +
Isnull(pvt.nov_CY, 0) + Isnull(pvt.Dec_CY, 0) AS This_Year
FROM
(SELECT Account AS [GL_Code], AccountDesc AS [GL Desc].......
My question is I have being tasked with amending this to exclude the current month from the total based on whatever the current month is at the time.
So at the moment (in December) I only need to calculate everything up to and including November. In January it will be everything up to and including December and so on.
What will be the best way to approach this? Will I need to perform a CASE for each scenario i.e. When Current month = 12 only add 1+2+....11 etc?
If anyone is interested I worked it out:
SELECT
pvt.*,
CASE
WHEN MONTH(GETDATE()) = 5 THEN Isnull(pvt.may_CY, 0)
WHEN MONTH(GETDATE()) = 6 THEN Isnull(pvt.may_CY, 0)
WHEN MONTH(GETDATE()) = 7 THEN Isnull(pvt.may_CY, 0) + Isnull(pvt.jun_CY, 0)
WHEN MONTH(GETDATE()) = 8 THEN Isnull(pvt.may_CY, 0) + Isnull(pvt.jun_CY, 0) + Isnull(pvt.jul_CY, 0)
WHEN MONTH(GETDATE()) = 9 THEN Isnull(pvt.may_CY, 0) + Isnull(pvt.jun_CY, 0) + Isnull(pvt.jul_CY, 0) + Isnull(pvt.aug_CY, 0)
WHEN MONTH(GETDATE()) = 10 THEN Isnull(pvt.may_CY, 0) + Isnull(pvt.jun_CY, 0) + Isnull(pvt.jul_CY, 0) + Isnull(pvt.aug_CY, 0)+Isnull(pvt.sep_CY, 0)
WHEN MONTH(GETDATE()) = 11 THEN Isnull(pvt.may_CY, 0) + Isnull(pvt.jun_CY, 0) + Isnull(pvt.jul_CY, 0) + Isnull(pvt.aug_CY, 0)+Isnull(pvt.sep_CY, 0)+ Isnull(pvt.oct_CY, 0)
WHEN MONTH(GETDATE()) = 12 THEN Isnull(pvt.may_CY, 0) + Isnull(pvt.jun_CY, 0) + Isnull(pvt.jul_CY, 0) + Isnull(pvt.aug_CY, 0)+Isnull(pvt.sep_CY, 0)+ Isnull(pvt.oct_CY, 0) + Isnull(pvt.nov_CY, 0)
WHEN MONTH(GETDATE()) = 1 THEN Isnull(pvt.may_CY, 0) + Isnull(pvt.jun_CY, 0) + Isnull(pvt.jul_CY, 0) + Isnull(pvt.aug_CY, 0)+Isnull(pvt.sep_CY, 0)+ Isnull(pvt.oct_CY, 0) + Isnull(pvt.nov_CY, 0) + Isnull(pvt.Dec_CY, 0)
WHEN MONTH(GETDATE()) = 2 THEN Isnull(pvt.may_CY, 0) + Isnull(pvt.jun_CY, 0) + Isnull(pvt.jul_CY, 0) + Isnull(pvt.aug_CY, 0)+Isnull(pvt.sep_CY, 0)+ Isnull(pvt.oct_CY, 0) + Isnull(pvt.nov_CY, 0) + Isnull(pvt.Dec_CY, 0) + Isnull(pvt.jan_CY, 0)
WHEN MONTH(GETDATE()) = 3 THEN Isnull(pvt.may_CY, 0) + Isnull(pvt.jun_CY, 0) + Isnull(pvt.jul_CY, 0) + Isnull(pvt.aug_CY, 0)+Isnull(pvt.sep_CY, 0)+ Isnull(pvt.oct_CY, 0) + Isnull(pvt.nov_CY, 0) + Isnull(pvt.Dec_CY, 0) + Isnull(pvt.jan_CY, 0) + Isnull(pvt.feb_CY, 0)
WHEN MONTH(GETDATE()) = 4 THEN Isnull(pvt.may_CY, 0)+ Isnull(pvt.jun_CY, 0) + Isnull(pvt.jul_CY, 0) + Isnull(pvt.aug_CY, 0)+Isnull(pvt.sep_CY, 0)+ Isnull(pvt.oct_CY, 0) + Isnull(pvt.nov_CY, 0) + Isnull(pvt.Dec_CY, 0) + Isnull(pvt.jan_CY, 0) + Isnull(pvt.feb_CY, 0) + Isnull(pvt.mar_CY, 0)
end as This_Year
FROM
(SELECT Account AS [GL_Code], AccountDesc AS [GL Desc].......