The multi-part identifier 'dbo.AdditionalInfo.UserDefined3' could not be bound - sql

Im having a problem with this :( is this because of my select statement? or any join? derived table? or my CASE syntax?
The error occurs the time I put this CASE syntax: CASE WHEN dbo.AdditionalInfo.UserDefined3 = 1 THEN 2
because before it is just:
CASE WHEN WorkOrder.DateCreated < (CASE WHEN (DATEPART(dw,
dbo.ToBeScheduled_InProgress.Start) = 2) THEN (ToBeScheduled_InProgress.Start + 0.625) - 3 ELSE (ToBeScheduled_InProgress.Start + 0.625) - 1 END) THEN 1 ELSE 2 END AS ScheduleTime
SELECT Start, UserDefined3, ItemNo, Name, TotalQtyRequired, PreviouslyCounted, QtyLeftToPick, LocationCode, Location, Rack, QtyInRack, PickQty, CellCode, UDMaterial, UDMaterialSort, ScheduleTimeFROM (SELECT dbo.ToBeScheduled_InProgress.Start, dbo.ItemSpecs.ItemNo, dbo.ItemSpecs.Name, SUM(ISNULL(dbo.ToBeScheduled_InProgress.RemainingQty, 0) * ISNULL(dbo.ItemSpecFullStruc.TotalQtyPerRoot, 0))
AS TotalQtyRequired, ISNULL(RackedInventory.PreviouslyCounted, 0) AS PreviouslyCounted, SUM(ISNULL(dbo.ToBeScheduled_InProgress.RemainingQty, 0) * ISNULL(dbo.ItemSpecFullStruc.TotalQtyPerRoot, 0))
- ISNULL(RackedInventory.PreviouslyCounted, 0) AS QtyLeftToPick, RackedInventory.LocationCode, RackedInventory.Location, RackedInventory.Rack, ISNULL(RackedInventory.QtyInRack, 0) AS QtyInRack,
ISNULL(CASE WHEN SUM(ISNULL(dbo.ToBeScheduled_InProgress.RemainingQty, 0) * ISNULL(dbo.ItemSpecFullStruc.TotalQtyPerRoot, 0)) - ISNULL(RackedInventory.PreviouslyCounted, 0)
< RackedInventory.QtyInRack THEN SUM(ISNULL(dbo.ToBeScheduled_InProgress.RemainingQty, 0) * ISNULL(dbo.ItemSpecFullStruc.TotalQtyPerRoot, 0)) - ISNULL(RackedInventory.PreviouslyCounted, 0)
ELSE RackedInventory.QtyInRack END, 0) AS PickQty, dbo.ToBeScheduled_InProgress.CellCode, dbo.ItemSpecs.Userdefined2 AS UDMaterial, CASE WHEN dbo.ItemSpecs.Userdefined2 IN ('Foam', 'Wood',
'Plastic Inner', 'Rubber') THEN 0 ELSE 1 END AS UDMaterialSort, CASE WHEN dbo.AdditionalInfo.UserDefined3 = 1 THEN 2 WHEN WorkOrder.DateCreated < (CASE WHEN (DATEPART(dw,
dbo.ToBeScheduled_InProgress.Start) = 2) THEN (ToBeScheduled_InProgress.Start + 0.625) - 3 ELSE (ToBeScheduled_InProgress.Start + 0.625) - 1 END) THEN 1 ELSE 2 END AS ScheduleTime
FROM dbo.ToBeScheduled_InProgress INNER JOIN
dbo.OpenCalendarDaysTable AS OpenCalendarDays ON dbo.ToBeScheduled_InProgress.Start BETWEEN OpenCalendarDays.CalendarDateForwardRangeStart AND
OpenCalendarDays.CalendarDateForwardRangeEnd AND OpenCalendarDays.CalendarLinkID IS NULL INNER JOIN
dbo.OpenCalendarDaysTable AS PriorOpenCalendarDays ON OpenCalendarDays.CalendarOpenDayID = PriorOpenCalendarDays.CalendarOpenDayID + 1 AND OpenCalendarDays.CalendarLinkID IS NULL
INNER JOIN
dbo.ItemSpecFullStruc ON dbo.ToBeScheduled_InProgress.ItemSpecID = dbo.ItemSpecFullStruc.RootItemSpecID INNER JOIN
dbo.ItemSpecs ON dbo.ItemSpecFullStruc.ChildItemSpecID = dbo.ItemSpecs.ItemSpecID LEFT OUTER JOIN
dbo.WorkOrder ON dbo.ToBeScheduled_InProgress.WorkOrderID = dbo.WorkOrder.WorkOrderID LEFT OUTER JOIN
(SELECT InventoryByLocation.ItemID, InventoryByLocation.ItemNo, InventoryByLocation.ItemDescription, InventoryByLocation.LocationCode, InventoryByLocation.Location, InventoryByLocation.Rack,
InventoryByLocation.QtyInRack, SUM(PreviouslyCounted.QtyInRack) AS PreviouslyCounted
FROM (SELECT Rack, SUM(ISNULL(QtyToStock, ' ')) AS QtyInRack, ItemID, ItemSpecID, LocationID
FROM dbo.InventoryItems WITH (NOLOCK)
GROUP BY ItemID, ItemSpecID, LocationID, Rack) AS PreviouslyCounted RIGHT OUTER JOIN
(SELECT Items_1.ItemNo, Items_1.Name AS ItemDescription, Locations_1.LocationCode, Locations_1.DescriptionMed AS Location, InventoryItems_1.Rack,
SUM(dbo.Val(ISNULL(InventoryItems_1.QtyToStock, ''))) AS QtyInRack, UOMs_1.UOMCode AS StockUOM, InventoryItems_1.ItemID, InventoryItems_1.ItemSpecID,
Locations_1.LocationID
FROM dbo.Items AS Items_1 WITH (NOLOCK) INNER JOIN
dbo.Locations AS Locations_1 WITH (NOLOCK) INNER JOIN
dbo.InventoryItems AS InventoryItems_1 WITH (NOLOCK) LEFT OUTER JOIN
dbo.UOMs AS UOMs_1 WITH (NOLOCK) ON InventoryItems_1.StockUOMID = UOMs_1.UOMID ON Locations_1.LocationID = InventoryItems_1.LocationID ON
Items_1.ItemID = InventoryItems_1.ItemID
WHERE (Locations_1.LocationID = 7)
GROUP BY Locations_1.LocationCode, Items_1.ItemNo, Locations_1.DescriptionMed, Items_1.Name, UOMs_1.UOMCode, InventoryItems_1.ItemID, InventoryItems_1.ItemSpecID,
Locations_1.LocationID, InventoryItems_1.Rack
HAVING (SUM(dbo.Val(ISNULL(InventoryItems_1.QtyToStock, ''))) > 0)) AS InventoryByLocation ON PreviouslyCounted.Rack < InventoryByLocation.Rack AND
PreviouslyCounted.LocationID = InventoryByLocation.LocationID AND PreviouslyCounted.ItemID = InventoryByLocation.ItemID
GROUP BY InventoryByLocation.ItemNo, InventoryByLocation.ItemDescription, InventoryByLocation.LocationCode, InventoryByLocation.Location, InventoryByLocation.Rack, InventoryByLocation.QtyInRack,
InventoryByLocation.ItemID) AS RackedInventory ON dbo.ItemSpecs.ItemID = RackedInventory.ItemID
WHERE (dbo.ToBeScheduled_InProgress.ExcludeFromFiniteScheduling = 0) AND (ISNULL(dbo.ItemSpecs.Userdefined2, '') <> 'Covering') AND (dbo.ItemSpecs.InventoryTrackingID > 1)
GROUP BY dbo.ToBeScheduled_InProgress.Start, dbo.ItemSpecs.ItemNo, dbo.ItemSpecs.Name, RackedInventory.Rack, ISNULL(RackedInventory.PreviouslyCounted, 0), RackedInventory.Location,
RackedInventory.LocationCode, dbo.ToBeScheduled_InProgress.CellCode, dbo.ItemSpecs.Userdefined2,
CASE WHEN dbo.AdditionalInfo.UserDefined3 = 1 THEN 2 WHEN WorkOrder.DateCreated < (CASE WHEN (DATEPART(dw, dbo.ToBeScheduled_InProgress.Start) = 2) THEN (ToBeScheduled_InProgress.Start + 0.625)
- 3 ELSE (ToBeScheduled_InProgress.Start + 0.625) - 1 END) THEN 1 ELSE 2 END, RackedInventory.QtyInRack
HAVING (SUM(ISNULL(dbo.ToBeScheduled_InProgress.RemainingQty, 0) * ISNULL(dbo.ItemSpecFullStruc.TotalQtyPerRoot, 0)) - ISNULL(RackedInventory.PreviouslyCounted, 0) > 0)) AS _RackSort_Lean_AMPM ORDER BY Start, LocationCode, Rack

Related

Returning LINE with no inner join match

I am trying to put a statement together the first part of the code works.
DECLARE #FYEND date, #YTD date, #PYTD date, #Openmonth date, #Monthtodatefrom date, #Monthtodateto date, #Priormonthdatefrom date, #Priormonthdateto date, #Currentmonth date
SET #FYEND = Dateadd(year,1,DATEADD(year,DATEDIFF(month,'19010701', getdate() ) /12,'19010701'))
SET #YTD = GETDATE()
SET #PYTD = DATEADD(YEAR,-1,#YTD)
SET #Openmonth = dateadd(DAY,1,dateadd(YEAR,-1,EOMONTH(#YTD,-1)))
SET #Monthtodatefrom = EOMONTH(getdate(),-2)
SET #Monthtodateto = Dateadd(DAY,1,eomonth(#ytd,-1))
SET #Priormonthdatefrom= DATEADD(YEAR,-1,#monthtodatefrom)
SET #Priormonthdateto= dateadd(year,-1,Dateadd(DAY,1,eomonth(#ytd,-1)))
SET #Currentmonth=dateadd(DAY,1,EOMONTH(getdate(),-1))
SELECT
b.T3,
b.Country_name,
b.Division_Name,
b.SHOP_NAME,
b.Shop_Type,
b.MTD_Result
FROM
(
SELECT
a.T3,
a.Country_name,
a.Division_Name,
a.SHOP_NAME,
a.Shop_Type,
sum(case when coa.EBIT in ('EBIT') then gl.Amount ELSE 0 END) as MTD_Result
FROM
(
SELECT
s.T3,
s.DIVISION_NAME as Division_Name,
s.SHOP_NAME,
s.COUNTRY_NAME as Country_name,
s.[Business Grouping] as Shop_Type
FROM Finance_PRD.dbo.Shops s
WHERE
s.DIVISION_NAME in ('NSWACT FCB Retail North', 'NSWACT FCB Retail South', 'Vicmania', 'The Heartland', 'SA FCB Retail', 'WANT FCB Retail', 'UT Leisure', 'TA Leisure', 'Contact Centre')
and s.BUSTYPE='ARET'
and s.[Open Date] < #Currentmonth
and s.[Close Date] is null
and s.T3 = '497088'
GROUP BY
s.T3,
s.SHOP_TYPE,
s.PRIMARY_STORE_T3,
s.DIVISION_NAME,
s.t3,
s.SHOP_NAME,
s.COUNTRY_NAME,
s.[Business Grouping],
s.BUSINESS_GROUPING_NAME,
s.SHOP_NAME) a
INNER JOIN Finance_PRD.ANZ.ConsolidatedAUD as gl
on a.T3 = gl.T3
INNER JOIN Finance_PRD.dbo.ChartOfAccounts coa
on gl.AccountCode = coa.Code
WHERE gl.Period > CASE WHEN MONTH(#Monthtodatefrom) <= 6 THEN
CONCAT(YEAR(#Monthtodatefrom), RIGHT(CONCAT('000', MONTH(#Monthtodatefrom) + 6), 3))
ELSE CONCAT(YEAR(#Monthtodatefrom) + 1, RIGHT(CONCAT('000', MONTH(#Monthtodatefrom) - 6), 3))
END and gl.Period < CASE WHEN MONTH(#Monthtodateto) <= 6 THEN
CONCAT(YEAR(#Monthtodateto), RIGHT(CONCAT('000', MONTH(#Monthtodateto) + 6), 3))
ELSE CONCAT(YEAR(#Monthtodateto) + 1, RIGHT(CONCAT('000', MONTH(#Monthtodateto) - 6), 3))
END
GROUP BY
a.T3,
a.Country_name,
a.Division_Name,
a.SHOP_NAME,
a.Shop_Type
)b
but when I want to join on a second statement it does not return a value, I require the second statement to be 0 if there is no join.
Second part of the code is here which I set below query b
Inner join Finance_PRD.ANZ.ConsolidatedAUD as gl
on b.T3 = gl.T3
Inner JOIN Finance_PRD.dbo.ChartOfAccounts coa
on gl.AccountCode = coa.Code
WHERE gl.Period > CASE WHEN MONTH(#Priormonthdatefrom) <= 6 THEN
CONCAT(YEAR(#Priormonthdatefrom), RIGHT(CONCAT('000', MONTH(#Priormonthdatefrom) + 6), 3))
ELSE CONCAT(YEAR(#Priormonthdatefrom) + 1, RIGHT(CONCAT('000', MONTH(#Priormonthdatefrom) - 6), 3))
END and gl.Period < CASE WHEN MONTH(#Priormonthdateto) <= 6 THEN
CONCAT(YEAR(#Priormonthdateto), RIGHT(CONCAT('000', MONTH(#Priormonthdateto) + 6), 3))
ELSE CONCAT(YEAR(#Priormonthdateto) + 1, RIGHT(CONCAT('000', MONTH(#Priormonthdateto) - 6), 3))
END
I've tried to understand all the different joins and even attempted to use is null, if and coalesce to no avail.
...................
LEFT JOIN
(
Finance_PRD.ANZ.ConsolidatedAUD as gl
INNER JOIN Finance_PRD.dbo.ChartOfAccounts coa on gl.AccountCode = coa.Code
) on a.T3 = gl.T3
WHERE gl.Period IS NULL OR (gl.Period > CASE WHEN MONTH(#Monthtodatefrom) <= 6 THEN ....)

SQL query taking longer time to execute

I'm trying to execute the query. It take 32 min to execute. I have tried NOLOCK but only optimized it with 3 min.
the query is given below:-
SELECT PO.payday, PO.facility, PO.department, PO.workcenter, PO.shift, PO.team, PO.orderno, PO.fg_productno,
PO.sfg_productno, NoCarton = '1', NoPack = 5, NoCigarette = PO.nocigarette, VNC.sampleid, VNC.comment,
VNC.createdby, SampleDateTime = dbo.AF_GetUTCToLocal(VNC.UTCStartDate),
SampleTime = Cast(CONVERT(CHAR(10), VNC.utcstartdate, 101) AS DATETIME), VNC.ncgroup, VNC.productcomponent,
VNC.nc, VNC.ncname, VNC.weightingfactor, VNC.ConsumerSensitive, VNC.[lowunits], VNC.[low %], VNC.[highunits],
VNC.[high %], VNC.vqi, VNC.deepcontrol,
--Modification done for CHE10045964
PO.ResourceClassName
FROM
(SELECT PayDay = WCS.payday, Facility = R.facility, Department = R.department, WorkCenter = R.workcenter,
Shift = WCS.workperiod, Team = SD.teamid, OrderNo = WO.orderno,
FG_ProductNo = P.productno + Isnull('.' + P.productrevision, ''),
SFG_ProductNo = CASE
WHEN UCHSC.attribute_ != P.productno
THEN UCHSC.attribute_
ELSE NULL
END,
WO.actualstartdate, WO.actualcompletiondate,
NoCigarette = dbo.Af_getunitcharacteristicattribute(OD.unitid,'ZPPPI_ITEM_PACK') ,
RC.Name as ResourceClassName
FROM order_header OH
INNER JOIN dbo.wip_order WO ON OH.orderno = WO.orderno
INNER JOIN dbo.order_detail OD ON OD.orderno = WO.orderno
INNER JOIN dbo. product P ON WO.productid = P.id
INNER JOIN dbo.resource_ R ON R.resourcename = WO.resourcename AND R.resourcetype = WO.resourcetype
Inner Join dbo.Resource_Class RC ON R.ResourceClassID = RC.ID
INNER JOIN dbo.work_center_work_schedule WCS ON WO.oawipentityid = WCS.id
INNER JOIN at_work_center_work_schedule_detail SD ON WCS.id = SD.workcenterworkscheduleid
LEFT JOIN dbo.unit_characteristic UCHSC ON UCHSC.unitid = OD.unitid
AND UCHSC.characteristic = 'ZPPPI_SPA_CIGARETTE'
WHERE OH.ordertype = 23
GROUP BY WCS.payday, R.facility, R.department, R.workcenter, WCS.workperiod, SD.teamid,
WO.orderno, P.productno + Isnull('.' + P.productrevision, ''),
CASE
WHEN UCHSC.attribute_ != P.productno THEN UCHSC.attribute_
ELSE NULL
END,
WO.actualstartdate, WO.actualcompletiondate,
dbo.Af_getunitcharacteristicattribute(OD.unitid,'ZPPPI_ITEM_PACK'),
RC.Name
) PO INNER JOIN
(
SELECT NC.orderno, NC.sampleid, NC.comment, NC.deepcontrol, NC.createdby, NC.utcstartdate, NC.ncgroup, NC.productcomponent,
NC.nc, NC.ncname, NC.weightingfactor, NC.ConsumerSensitive, NC.[lowunits], NC.[low %], NC.[highunits], NC.[high %],
VQI = Round(NC.weightingfactor * ( Log (1 + [low %] / 3.0 + [high %]) ), 0),
--Added By Sukanya Biswas(CHE10045964)
NC.WorkCenter
FROM (SELECT orderno, b.sampleid, b.comment, b.deepcontrol, b.utcstartdate, b.ncgroup, b.productcomponent,
b.nc, b.ncname, b.weightingfactor, b.ConsumerSensitive, b.createdby,
[LowUnits] = Isnull(b.[1], 0),
[Low %] = CASE CONVERT(NVARCHAR(1),b.deepcontrol) + b.ncgroup
WHEN '0Bundle' THEN CASE WHEN (Isnull(b.[1], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 100 END
WHEN '1Bundle' THEN CASE WHEN (Isnull(b.[1], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 100 END
WHEN '0Pack' THEN CASE WHEN (Isnull(b.[1], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * NoofCigarette END
WHEN '1Pack' THEN CASE WHEN (Isnull(b.[1], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * NoofCigarette END
WHEN '0Cigarette' THEN CASE WHEN (Isnull(b.[1], 0) * 5 ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 5 END
WHEN '1Cigarette' THEN CASE WHEN (Isnull(b.[1], 0) * 1 ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 1 END
WHEN '0Filter' THEN CASE WHEN (Isnull(b.[1], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 10 END
WHEN '1Filter' THEN CASE WHEN (Isnull(b.[1], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 10 END
ELSE Isnull(b.[1], 0)
END, [HighUnits] = Isnull(b.[2], 0),
[High %] = CASE CONVERT(NVARCHAR(1),b.deepcontrol) + b.ncgroup
WHEN '0Bundle' THEN CASE WHEN (Isnull(b.[2], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 100 END
WHEN '1Bundle' THEN CASE WHEN (Isnull(b.[2], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 100 END
WHEN '0Pack' THEN CASE WHEN (Isnull(b.[2], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * NoofCigarette END
WHEN '1Pack' THEN CASE WHEN (Isnull(b.[2], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * NoofCigarette END
WHEN '0Cigarette' THEN CASE WHEN (Isnull(b.[2], 0) * 5 ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 5 END
WHEN '1Cigarette' THEN CASE WHEN (Isnull(b.[2], 0) * 1 ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 1 END
WHEN '0Filter' THEN CASE WHEN (Isnull(b.[2], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 10 END
WHEN '1Filter' THEN CASE WHEN (Isnull(b.[2], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 10 END
ELSE Isnull(b.[2], 0)
END ,
--Added By Sukanya Biswas(CHE10045964)
B.WorkCenter
FROM (SELECT D .orderno, SampleID = DTS.id,
--Added By Sukanya Biswas(CHE10045964)
DL.WorkCenter,
Comment = CASE Isnull(DTS.comment_, '')
WHEN '' THEN 'N/A'
ELSE DTS.comment_
END, UTCStartDate = DTS.actualstartdate, NC.ncgroup, NC.productcomponent, NC.nc, NC.ncname,
NC.weightingfactor, NC.ConsumerSensitive,
Severity = Isnull(QD.qualitydefectseverityid, 0),
QD.noofdefects, DTS.createdby, DeepControl = DTS.overridesumresults,
NoofCigarette = dbo.Af_getunitcharacteristicattribute(OD.unitid,'ZPPPI_ITEM_PACK')
FROM dbo.disposition D
INNER JOIN dbo.disposition_line DL ON D .disposition = DL.disposition
--Inner Join dbo.Work_Center WC ON DL.Workcenter = WC.Workcenter
INNER JOIN dbo.disposition_test DT ON DT.disposition = D .disposition
AND DT.linesequenceno = DL.linesequenceno
INNER JOIN dbo.disposition_test_sample DTS ON DTS.dispositiontestid = DT.id
LEFT JOIN quality_defect QD ON QD.dispositiontestsampleid = DTS.id
INNER JOIN dbo.AV_RPT_VSI_Nonconformity NC ON Isnull(QD.defectreasoncode, '00.00.00') = NC.nc
LEFT JOIN ORDER_DETAIL OD ON OD.ORDERNO=D.ORDERNO
WHERE DL.linecode = 'VQ'
) A
PIVOT (Sum(a.noofdefects)
FOR severity IN ([1],[2]))
B)
NC
As per your query filter and columns needed, please make index on respected columns.
By default SQL will create clustered index on your primary key, but you may create some other unclustered index on your table to make your execution faster.
You may find this link for your reference or Google it there are hundreds of article available on Internet for same.
"https://learn.microsoft.com/en-us/sql/t-sql/statements/create-index-transact-sql?view=sql-server-2017"

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 Command Not Properly Ended

SELECT SUM(nvl(DYRCVDWT, 0)) + SUM(nvl(RCVDWT, 0)) + SUM(nvl(rcvdafpwt, 0)) - SUM(nvl(retdwt, 0)) INTO netwt
FROM YARNLEDGER yl
(SELECT D.PROFILECODE, MAX(CLOSINGDATE)SDATE FROM PARTYSTOCKCLOSING D WHERE D.DEPT = 'Y' AND NVL(D.POSTED, 'N') = 'Y' GROUP BY D.PROFILECODE) SAD
WHERE yl.PROFILECODE = :PROFILECODE
AND Yl.PROFILECODE = SAD.PROFILECODE(+)
AND Yl.DOCUMENTDATE>SAD.SDATE
there are missing a comma in the FROM after the "yarnledger yl"
SELECT SUM(nvl(dyrcvdwt, 0)) + SUM(nvl(rcvdwt, 0)) + SUM(nvl(rcvdafpwt, 0)) - SUM(nvl(retdwt, 0))
INTO netwt
FROM yarnledger yl ,(SELECT d.profilecode
,MAX(closingdate) sdate
FROM partystockclosing d
WHERE d.dept = 'Y'
AND nvl(d.posted, 'N') = 'Y'
GROUP BY d.profilecode) sad
WHERE yl.profilecode = :profilecode
AND yl.profilecode = sad.profilecode(+)
AND yl.documentdate > sad.sdate
next time use a clearer query structure:
WITH sad as (SELECT d.profilecode
,MAX(closingdate) sdate
FROM partystockclosing d
WHERE d.dept = 'Y'
AND nvl(d.posted, 'N') = 'Y'
GROUP BY d.profilecode)
SELECT SUM(nvl(dyrcvdwt, 0)) + SUM(nvl(rcvdwt, 0)) + SUM(nvl(rcvdafpwt, 0)) - SUM(nvl(retdwt, 0))
INTO netwt
FROM yarnledger yl
LEFT OUTER JOIN sad
ON yl.profilecode = sad.profilecode
AND yl.documentdate > sad.sdate
WHERE yl.profilecode = :profilecode

Create Clustered/Non Clustered Index in view

I am having a view which returns value to a table. The process takes a long time... So I felt it works better if go for indexing on view. Can anyone plz guide me to add index to view.
ALTER View [dbo].[GetApplicationBudgetAndUtilized]
as
Select *, (convert(money,isnull(TotalBudget,0)) - convert(money,isnull(Utilized,0))) as [Left] from (
SELECT Distinct PM.PKID AS ProgramID, F.PKID as FundID, I.PKID as ProjectID,
MYB.PKID AS MultiYearBudgetID,
(Select Isnull(Sum(IsNull(PBC1.BudgetAmount,0)),0) from ProgramBudgetConfiguration PBC1
Where pbc1.MultiYearBgtIdFkId = pbc.MultiYearBgtIdFkId and PBC1.IsActive = 1 and LOVBudgetTypeIDFKID = 'BT_INC' group
by pbc1.MultiYearBgtIdFkId) AS TotalProgramBudget,
App.TotalBudget,
I.PKID,
(Case when exists (Select 'x' from InstallationTransactionHeader Where ParentPrjNumber = I.PKID and IsDelete = 0)
then
(case
when not exists (select cast(isnull(I1.CustInstallIncAmt,0.00) + isnull(I1.SPInstIncentiveAmt,0.00) + isnull(I1.ThirdPartyIncentive,0.00) as Money)
from InstallationTransactionHeader I1 where I1.ParentPrjNumber is not null and I1.StatusFKID in ('ITS_SUB','ITS_APP','ITS_VRF') and
I1.ParentPrjNumber = I.PKID and I1.FundRequestIDFKID is not null) then (select '0')
else
(select isnull(sum(cast(isnull(I1.CustInstallIncAmt,0.00) + isnull(I1.SPInstIncentiveAmt,0.00) + isnull(I1.ThirdPartyIncentive,0.00) as Money)),0)
from InstallationTransactionheader I1 where I1.StatusFKID in ('ITS_SUB','ITS_APP','ITS_VRF') and I1.ParentPrjNumber is not null and
I1.ParentPrjNumber = I.PKID and I1.isdelete = 0 and I1.FundRequestIDFKID is not null group by I1.parentPrjNumber)
End)
else
--isnull(cast(isnull(I.CustInstallIncAmt,0.00) + isnull(I.SPInstIncentiveAmt,0.00) + isnull(I.ThirdPartyIncentive,0.00) as Money),0)
(case
when not exists (select isnull(cast(isnull(I.CustInstallIncAmt,0.00) + isnull(I.SPInstIncentiveAmt,0.00) + isnull(I.ThirdPartyIncentive,0.00) as Money),0) from
InstallationTransactionHeader I where StatusFKID in ('ITS_SUB','ITS_APP','ITS_VRF') and IsDelete = 0 and
PKID = I.PKID and I.FundRequestIDFKID is not null) then 0--(select '0')
else
(select isnull(sum(cast(isnull(I1.CustInstallIncAmt,0.00) + isnull(I1.SPInstIncentiveAmt,0.00) + isnull(I1.ThirdPartyIncentive,0.00) as Money)),0)
from InstallationTransactionheader I1 where I1.StatusFKID in ('ITS_SUB','ITS_APP','ITS_VRF') and IsDelete = 0 and I1.FundRequestIDFKID is not null and
PKID = I.PKID)
End)
End) as Utilized
--Cast(App.TotalBudget - (isnull(I.CustInstallIncAmt,0.00) + isnull(I.SPInstIncentiveAmt,0.00) + isnull(I.ThirdPartyIncentive,0.00)) as Money) as [Left]
FROM
( SELECT PKID as FundID, ProgramID AS ProgramID, (ISNULL(IncentiveAmount,0.00) + ISNULL(CustInstallIncAmt, 0.00) + ISNULL(SPInstIncentiveAmt, 0.00) ) AS TotalBudget
FROM dbo.FundRequestHeader AS F WHERE (IsDelete = 0) AND (IsActive = 1) AND (StatusFKID in ('IAS_APP','IAS_CAN'))) AS App
INNER JOIN dbo.ProgramMaster AS PM
INNER JOIN dbo.MultiYearBudget AS MYB ON PM.PKID = MYB.ProgramIDFKID
INNER JOIN dbo.ProgramBudgetConfiguration AS PBC ON MYB.PKID = PBC.MultiYearBgtIdFkId ON App.ProgramID = PM.PKID
INNER JOIN dbo.FundRequestHeader AS F ON F.PKID = App.FundID
INNER JOIN dbo.InstallationTransactionHeader AS I ON I.FundRequestIDFKID = F.PKID
WHERE (PM.IsActive = 1) AND (MYB.IsActive = 1) AND (PBC.IsActive = 1) AND
(PBC.LOVBudgetTypeIDFKID = 'BT_INC') And (F.StatusFKID in ('IAS_APP','IAS_CAN'))
--and (1=case when(select ProgramTypeIDFKID from InstallationTransactionHEader where ProgramTypeIDFKID='IT_PRE' and ParentPrjNumber is null and PaymentSchedule=1)='IT_PRE' then 0 else 1 end)
--and I.ProgramTypeIDFKID <> 'IT_PRE' or I.PaymentSchedule = 0 or (I.ProgramTypeIDFKID = 'IT_PRE' and I.PaymentSchedule = 1 and I.ParentPrjNumber is not null)
and MYB.PKID = F.BudgetPeriodID and ((MYB.IsActive = 1))-- or ((MYB.status = 0) and F.StatusFKID ='IAS_APP'))
and (MYB.Status = 1 or (MYB.Status =(case when exists(select M.status from MultiYearBudget M, FundRequestHeader F
where F.ProgramID=M.ProgramIDFKID and F.ProgramTypeIDFKID <>'IT_FCFS' and M.Pkid=F.BudgetPeriodID
and F.StatusFKID='IAS_APP' and F.ProgramID=PM.PKID and M.Status=0 )then 0 else 1 end))
)
)temp
GO
Indexed views have certain limitations
In your case, I can immediately see some blockers
SELECT *
Derived tables
So read this article, and see how far you get...
However, you should be able to look the execution plan identify bottlenecks where you can add indexes to the bases tables