Related
I'm trying to develop a query and i got something like this
SELECT a.No,
a.Finish,
a.Shift,
a.McCode,
d.NAME,
b.ItemCode,
b.ItemName,
b.Qty,
b.LotNo,
b.Description,
CASE
WHEN b.Description LIKE '%not good%' THEN 'NG'
ELSE 'OK'
END AS OKNG,
c.ItemCode AS matcode,
c.LotNo AS matlot,
CASE
WHEN e.GroupName = 'CONTACT' THEN 'CONTACT'
ELSE 'Coil/Silver/Wire'
END AS GroupName,
( c.Qty / ( a.Qty + a.QtyNg ) ) * b.Qty AS materialused
FROM PPRDDLV a
LEFT JOIN ICMUTTRAN b
ON a.PrdNo = b.TranNo
AND a.No = b.TranId
LEFT JOIN ICMUTTRAN c
ON a.PrdNo = c.TranNo
AND a.Finish = c.DatePost
AND c.TranTypeID = 6
AND c.LotNo <> '0'
LEFT JOIN popr d
ON a.OprCode = d.Code
LEFT JOIN ICITEM e
ON c.ItemId = e.id
WHERE c.qty IS NOT NULL
AND b.ItemCode IS NOT NULL
I got around 49000 records in around 2 seconds, then I wan't to pivot a column that has 2 kind of value, so I turned it to something like this
SELECT no,
finish,
shift,
mccode,
NAME,
itemcode,
itemname,
qty,
lotno,
description,
okng,
matcode,
matlot
FROM (SELECT a.No,
a.Finish,
a.Shift,
a.McCode,
d.NAME,
b.ItemCode,
b.ItemName,
b.Qty,
b.LotNo,
b.Description,
CASE
WHEN b.Description LIKE '%not good%' THEN 'NG'
ELSE 'OK'
END AS OKNG,
c.ItemCode AS matcode,
c.LotNo AS matlot,
CASE
WHEN e.GroupName = 'CONTACT' THEN 'CONTACT'
ELSE 'Coil/Silver/Wire'
END AS GroupName,
( c.Qty / ( a.Qty + a.QtyNg ) ) * b.Qty AS materialused
FROM PPRDDLV a
LEFT JOIN ICMUTTRAN b
ON a.PrdNo = b.TranNo
AND a.No = b.TranId
LEFT JOIN ICMUTTRAN c
ON a.PrdNo = c.TranNo
AND a.Finish = c.DatePost
AND c.TranTypeID = 6
AND c.LotNo <> '0'
LEFT JOIN popr d
ON a.OprCode = d.Code
LEFT JOIN ICITEM e
ON c.ItemId = e.id
WHERE c.qty IS NOT NULL
AND b.ItemCode IS NOT NULL) AS a
PIVOT (Max(materialused)
FOR groupname IN ([CONTACT],
[Coil/Silver/Wire])) AS b
but the query won't complete even after 10 minutes, it won't even show a single records. beside that one, the first query before I used pivot, I put an order by a.no but when I executed it, the result only shows to record 105 but the query is still working and no more record was loaded.
can anyone help me find out what's going on?
thank you!
Here's the sample data collected from the inner query and the expected value after the query.
enter image description here
I realize that I selected "matcode" in the outer select while it shouldn't be there (still didn't work though, and note for the column "material used", I'll be using it later after the pivot is done)
Try using conditional aggregate instead of pivot.
SELECT no,
finish,
shift,
mccode,
NAME,
itemcode,
itemname,
qty,
lotno,
description,
okng,
matcode,
matlot,
[CONTACT] = Max(CASE WHEN GroupName = 'CONTACT' THEN materialused END),
[Coil/Silver/Wire] = Max(CASE WHEN GroupName <> 'CONTACT' THEN materialused END)
FROM (<inner query>) AS a
GROUP BY no,
finish,
shift,
mccode,
NAME,
itemcode,
itemname,
qty,
lotno,
description,
okng,
matcode,
matlot
---IF you don't have index on filter columns then try to apply for performance
SELECT a.No,
a.Finish,
a.Shift,
a.McCode,
d.NAME,
b.ItemCode,
b.ItemName,
b.Qty,
b.LotNo,
b.Description,
CASE WHEN b.Description LIKE '%not good%' THEN 'NG'
ELSE 'OK'
END AS OKNG,
c.ItemCode,
c.LotNo,
MAX(CASE WHEN e.groupname ='CONTACT' THEN ( c.Qty / ( a.Qty + a.QtyNg ) ) * b.Qty END)OVER(ORDER BY a.no) AS [CONTACT],
MAX(CASE WHEN e.groupname ='Coil/Silver/Wire' THEN ( c.Qty / ( a.Qty + a.QtyNg ) ) * b.Qty END)OVER(ORDER BY a.no) AS [Coil/Silver/Wire]
FROM PPRDDLV a WITH(NOLOCK)
LEFT JOIN ICMUTTRAN b WITH(NOLOCK)
ON a.PrdNo = b.TranNo
AND a.No = b.TranId
LEFT JOIN ICMUTTRAN c WITH(NOLOCK)
ON a.PrdNo = c.TranNo
AND a.Finish = c.DatePost
AND c.TranTypeID = 6
AND c.LotNo <> '0'
LEFT JOIN popr d WITH(NOLOCK)
ON a.OprCode = d.Code
LEFT JOIN ICITEM e
ON c.ItemId = e.id
WHERE c.qty IS NOT NULL
AND b.ItemCode IS NOT NULL
I've got a query which returns 8 columns, 2 of them are sub queries which returns the maximum date. I would like to create 9th column which will return a number, asterisk or something to highlight the rows where date in column 1 is bigger than in column 2 but still keep all the rows. Is it possible somehow?
Edit:
this is the query
The columns I want to see the differences in are MaxExpDateGB and MaxExpDatePH
select
i.ITEM,
i.COMPANY,
count(distinct i.LOGISTICS_UNIT) as LocationsGB,
sum(on_hand_qty) as StockGB,
(select
Count(distinct location)
from
LOCATION_INVENTORY b where b.ITEM = i.ITEM and b.TEMPLATE_FIELD1 = '139' and b.TEMPLATE_FIELD4 is not null and b.TEMPLATE_FIELD5 is null) as LocationsPH,
(select
sum(on_hand_qty)
from
LOCATION_INVENTORY b where b.ITEM = i.ITEM and b.TEMPLATE_FIELD1 = '139' and b.TEMPLATE_FIELD4 is not null and b.TEMPLATE_FIELD5 is null) as StockPH,
MAX(i.Expiration_DATE) as MaxExpDateGB,
(select
MAX(a.Expiration_DATE)
from
LOCATION_INVENTORY a where a.ITEM = i.ITEM and a.TEMPLATE_FIELD1 = '139' and a.TEMPLATE_FIELD4 is not null and a.INVENTORY_STS = 'available' ) as MaxExpDatePH
from
LOCATION l inner join LOCATION_INVENTORY i on l.LOCATION = i.LOCATION inner join ITEM t on i.ITEM = t.ITEM
where
t.USER_DEF6 = '10'
and i.LOCATION = '000-gb-01'
group by
i.item,i.company
Without any refactoring
select *, case when LocationsPH > StockPH then '*' end flag
from (
select
i.ITEM,
i.COMPANY,
count(distinct i.LOGISTICS_UNIT) as LocationsGB,
sum(on_hand_qty) as StockGB,
(select
Count(distinct location)
from
LOCATION_INVENTORY b where b.ITEM = i.ITEM and b.TEMPLATE_FIELD1 = '139' and b.TEMPLATE_FIELD4 is not null and b.TEMPLATE_FIELD5 is null
) as LocationsPH,
(select
sum(on_hand_qty)
from
LOCATION_INVENTORY b where b.ITEM = i.ITEM and b.TEMPLATE_FIELD1 = '139' and b.TEMPLATE_FIELD4 is not null and b.TEMPLATE_FIELD5 is null
) as StockPH,
MAX(i.Expiration_DATE) as MaxExpDateGB,
(select
MAX(a.Expiration_DATE)
from
LOCATION_INVENTORY a where a.ITEM = i.ITEM and a.TEMPLATE_FIELD1 = '139' and a.TEMPLATE_FIELD4 is not null and a.INVENTORY_STS = 'available'
) as MaxExpDatePH
from
LOCATION l
inner join LOCATION_INVENTORY i on l.LOCATION = i.LOCATION inner join ITEM t on i.ITEM = t.ITEM
where
t.USER_DEF6 = '10'
and i.LOCATION = '000-gb-01'
group by
i.item,i.company
) t
I'm trying to count the total number of open diary records for each user.
My problem is the user names have three different prefixes. CC YY or none.
I can replace the prefixes making the names identical but I'm having trouble grouping them by this modified name. The data is spread across three tables and I need to exclude closed and inactive records.
This simplified query returns an example of the un-grouped results I want.
select sname
,( Select count(lDiaryHeaderID)
FROM DiaryHeader
inner join OwnersCorporation on lObjectID = lOwnersCorporationID
where
sObjectType = 'B'
AND DiaryHeader.bRecordClosed = 'N'
AND DiaryHeader.dActionDueDate < cast (GETDATE() as DATE)
AND OwnersCorporation.bManaged = 'Y'
AND tbluser.lUserID = strata.dbo.OwnersCorporation.lUserID
) as TotalOverDue
FROM tblUser
WHERE bActive = 'Y'
AND bManager = 'Y'
ORDER by sName
Result
sname TotalOverDue
Belinda Smith 525
CC Belinda Smith 18
CC Julie Brown 13
CC Kris White 0
CC Sharon Towell 38
Colleen Black 131
Jessica Jones 166
Joanne Beigh 284
Julie Brown 449
YS Belinda Smith 31
YS Colleen Black 0
YS Joanne Beigh 21
What I want to do is remove the CC and the YS prefix from the name
and group them as a single entry and add the totals together.
Desired Result
sname TotalOverDue
Belinda Smith 574
Julie Brown 462
Kris White 0
Sharon Towell 38
Colleen Black 131
Jessica Jones 166
Joanne Beigh 305
I came up with this.
select Replace(Replace(sName, 'CC ',''), 'YS ','')
,( Select count(lDiaryHeaderID)
FROM DiaryHeader
inner join OwnersCorporation on lObjectID = lOwnersCorporationID
where
sObjectType = 'B'
AND DiaryHeader.bRecordClosed = 'N'
AND DiaryHeader.dActionDueDate < cast (GETDATE() as DATE)
AND OwnersCorporation.bManaged = 'Y'
AND tbluser.lUserID = strata.dbo.OwnersCorporation.lUserID
) as TotalOverDue
FROM tblUser
WHERE bActive = 'Y'
AND bManager = 'Y'
group by sName
However I get this error message
Column 'tblUser.lUserID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
If I put lUserID in the group by clause it just shows the duplicated the usernames as expected.
Any ideas where I'm going wrong and how I should be doig this.
Thanks
David
UPDATE:
My actual solution has multiple columns and I removed two of them to simplify my question. Now that I'm trying to expand it again I have run into more problems.
Here is my attempt to add the other two columns back in. DueToday and TotalDue however my totals are snowballing.
Update 2
Thanks to Phylyp's eagle eye. He spotted some cut and paste errors and this code now returns the desired result.
Thanks to everyone who responded with some very interesting and diverse solutions. I'll stick with the first one that works :)
select Replace(Replace(sName, 'CC ', ''), 'YS ', ''),
coalesce(sum(od.cnt), 0) as TotalOverDue,
coalesce(sum(dt.cnt), 0) as DueToday,
coalesce(sum(td.cnt), 0) as TotalDue
from tblUser u
left join (
select oc.lUserID,
count(lDiaryHeaderID) cnt
from DiaryHeader dh
inner join OwnersCorporation oc on lObjectID = lOwnersCorporationID
where sObjectType = 'B'
and dh.bRecordClosed = 'N'
and dh.dActionDueDate < cast(GETDATE() as date)
and oc.bManaged = 'Y'
group by oc.lUserID
) od on u.lUserID = od.lUserID
left join (
select oc.lUserID,
count(lDiaryHeaderID) cnt
from DiaryHeader dh
inner join OwnersCorporation oc on lObjectID = lOwnersCorporationID
where sObjectType = 'B'
and dh.bRecordClosed = 'N'
and dh.dActionDueDate = cast(GETDATE() as date)
and oc.bManaged = 'Y'
group by oc.lUserID
) dt on u.lUserID = dt.lUserID
left join (
select oc.lUserID,
count(lDiaryHeaderID) cnt
from DiaryHeader dh
inner join OwnersCorporation oc on lObjectID = lOwnersCorporationID
where sObjectType = 'B'
and dh.bRecordClosed = 'N'
--and dh.dActionDueDate < cast(GETDATE() as date)
and oc.bManaged = 'Y'
group by oc.lUserID
) td on u.lUserID = td.lUserID
where bActive = 'Y'
and bManager = 'Y'
group by Replace(Replace(sName, 'CC ', ''), 'YS ', '')
First you need to group by the replace expression instead of the column sName. Also, be careful with the replace as it replaces the match anywhere in the string.
Second, replace the correlated subquery with a left join.
select Replace(Replace(sName, 'CC ', ''), 'YS ', ''),
coalesce(sum(od.cnt), 0) as TotalOverDue
from tblUser u
left join (
select oc.lUserID,
count(ldhID) cnt
from DiaryHeader dh
inner join OwnersCorporation oc on lObjectID = locID
where sObjectType = 'B'
and dh.bRecordClosed = 'N'
and dh.dActionDueDate < cast(GETDATE() as date)
and oc.bManaged = 'Y'
group by oc.lUserID
) od on u.lUserID = od.lUserID
where bActive = 'Y'
and bManager = 'Y'
group by Replace(Replace(sName, 'CC ', ''), 'YS ', '')
Yes it will give the error because in your code you are using GROUP BY clause with out aggregate function.
Please try the script below.
Select a.sName,Sum(TotalOverDue) As TotalOverDue
FROM (
select Replace(Replace(sName, 'CC ',''), 'YS ','') As sName
,( Select count(lDiaryHeaderID)
FROM DiaryHeader
inner join OwnersCorporation on lObjectID = lOwnersCorporationID
where
sObjectType = 'B'
AND DiaryHeader.bRecordClosed = 'N'
AND DiaryHeader.dActionDueDate < cast (GETDATE() as DATE)
AND OwnersCorporation.bManaged = 'Y'
AND tbluser.lUserID = strata.dbo.OwnersCorporation.lUserID
) as TotalOverDue
FROM tblUser
WHERE bActive = 'Y'
AND bManager = 'Y' ) a
Group By sName
Here's my recommendation below.
I'm using a CASE expression to check if the name starts with CC or YS, and if so, remove the first 3 letters. This ensures that any CC/YS present within the name itself (e.g. as initials) aren't inadvertently removed, as is the case with the REPLACE() function.
SELECT
tblUserNameNormalized.sNameNormalized
, COALESCE(SUM(od.cnt), 0) AS TotalOverDue
, COALESCE(SUM(dt.cnt), 0) AS DueToday
, COALESCE(SUM(td.cnt), 0) AS TotalDue
FROM
(
SELECT
lUserID
, CASE
-- Check if the name starts with CC or YS, and skip the first 3 letters in that case
WHEN sName LIKE ('CC%') THEN SUBSTRING(sName, 4, LEN(sName) - 3)
WHEN sName LIKE ('YS%') THEN SUBSTRING(sName, 4, LEN(sName) - 3)
-- Else use the name as-is
ELSE sName
END AS sNameNormalized
FROM
tblUser
WHERE bActive = 'Y'
AND bManager = 'Y'
) as tblUserNameNormalized
LEFT JOIN (
select oc.lUserID,
count(lDiaryHeaderID) cnt
from DiaryHeader dh
inner join OwnersCorporation oc on lObjectID = lOwnersCorporationID
where sObjectType = 'B'
and dh.bRecordClosed = 'N'
and dh.dActionDueDate < cast(GETDATE() as date)
and oc.bManaged = 'Y'
group by oc.lUserID
) od on tblUserNameNormalized.lUserID = od.lUserID
LEFT JOIN (
select oc.lUserID,
count(lDiaryHeaderID) cnt
from DiaryHeader dh
inner join OwnersCorporation oc on lObjectID = lOwnersCorporationID
where sObjectType = 'B'
and dh.bRecordClosed = 'N'
and dh.dActionDueDate = cast(GETDATE() as date)
and oc.bManaged = 'Y'
group by oc.lUserID
) dt on tblUserNameNormalized.lUserID = dt.lUserID
LEFT JOIN (
select oc.lUserID,
count(lDiaryHeaderID) cnt
from DiaryHeader dh
inner join OwnersCorporation oc on lObjectID = lOwnersCorporationID
where sObjectType = 'B'
and dh.bRecordClosed = 'N'
--and dh.dActionDueDate < cast(GETDATE() as date)
and oc.bManaged = 'Y'
group by oc.lUserID
) td on tblUserNameNormalized.lUserID = td.lUserID
GROUP BY tblUserNameNormalized.sNameNormalized
You can use Replace like this then group what ever you want:
declare #CC varchar(20)
declare #YS varchar(20)
Set #CC = 'CC sample name'
Set #YS = 'CC sample name'
select replace(#CC,'CC ',''),replace(#YS,'YS ','');
SELECT FutureDatedEmployeeRecordsKey INTO #FutureDatedExclude
FROM dbo.vwRptDimEmployee_FutureDated FD1
WHERE EXISTS (SELECT 1 FROM dbo.vwRptDimEmployeeAll EE1 WITH (NOLOCK)
WHERE FD1.EmployeeID = EE1.EmployeeID AND FD1.EmployeeRecord = EE1.EmployeeRecord
AND FD1.JobEffectiveDate = EE1.JobEffectiveDT AND FD1.JobEffectiveDateSequence = EE1.JobEffectiveDateSequence
AND FD1.ActionCode = EE1.ActionCode AND FD1.ActionReasonCode = EE1.ActionReasonCode)
declare #JobStartDate date = '07/01/2014', #JobEndDate date = '06/30/2015'
SELECT DISTINCT
E.LastName,
E.SecondLastName,
E.FirstName,
E.MiddleName,
E.PreferredName,
E.PreferredFirstName,
E.NameAC,
E.LastNameAC,
E.FirstNameAC,
E.MiddleNameAC,
E.GUI,
E.EmployeeID,
E.LPN,
E.GPN,
E.EmployeeRecord,
E.JobEffectiveDT JobEffectiveDate,
E.JobEffectiveDateSequence,
E.ActionCode,
E.Action,
E.ActionDate,
E.ActionReasonCode,
AR.Description ActionReason,
E.EmployeeStatusCode,
E.EmployeeStatusDesc,
CASE WHEN YEAR(E.LeaveEffectiveDT) > 2100 THEN NULL ELSE E.LeaveEffectiveDT END LeaveEffectiveDate,
CASE WHEN YEAR(E.ExpectedReturnDate) > 2100 THEN NULL ELSE E.ExpectedReturnDate END ExpectedReturnDate,
E.FullPartTime,
E.ShiftCode FWACode,
E.Shift FWAName,
E.TeleWork,
E.StandardHoursFrequency,
E.StandardHours,
E.FTE,
E.PaidFTE,
E.OvertimeEligibility,
E.EmployeeClassCode,
E.EmployeeClass,
E.RegularVersusTemporary RegularTemporary,
E.EmployeeType,
E.PersonnelStatusDesc,
E.PersonOrganizationRelationshipCode,
P.PersonOfInterest,
P.PersonOfInterestDesc,
E.PaygroupCode,
E.EmployeeCategoryCode,
E.EmployeeSubcategoryCode,
P.EmploymentCategory,
E.NonEmployeeNonWorkTypeCD NonEmployeeNonWorkTypeCode,
P.NonEmployeeNonWorkTypeDesc,
A.GlobalAssignmentProgramCD GlobalAssignmentProgramCode,
A.GlobalAssignmentProgramDesc,
CASE WHEN YEAR(E.GlobalAssignmentStartDT) > 2100 THEN NULL ELSE E.GlobalAssignmentStartDT END GlobalAssignmentStartDate,
CASE WHEN YEAR(E.GlobalAssignmentEndDT) > 2100 THEN NULL ELSE E.GlobalAssignmentEndDT END GlobalAssignmentEndDate,
E.InPatExPatStatus,
E.HomeCountry,
E.HomeHostCountry HostCountry,
CASE WHEN YEAR(E.EYStartDate) > 2100 THEN NULL ELSE E.EYStartDate END EYStartDate,
CASE WHEN YEAR(E.LastRehireDate) > 2100 THEN NULL ELSE E.LastRehireDate END LastRehireDate,
CASE WHEN YEAR(E.SeniorityDate) > 2100 THEN NULL ELSE E.SeniorityDate END SeniorityDate,
CASE WHEN YEAR(E.EmployeeEffectiveDate) > 2100 THEN NULL ELSE E.EmployeeEffectiveDate END CurrentEmploymentDate,
CASE WHEN YEAR(E.PartnerAdmissionDate) > 2100 THEN NULL ELSE E.PartnerAdmissionDate END PartnerAdmissionDate,
R.RankCDName RankCodeName,
E.Rank,
R.RankDesc,
E.BusinessTitle,--NEW
R.RankGroup1,--NEW
E.GFISRank,
E.ExperienceLevel,
E.GlobalGrade,
E.JobCode,--NEW
E.JobCDDesc JobCodeDesc,--NEW
E.DepartmentCode,
E.DepartmentName,
E.CompanyCode,
C.Description Company,
C.DescrAc CompanyAC,
E.ManagerialCountryCD ManagerialCountry,
O.CodeBlock,
O.BUCD BU,
O.OUCD OU,
O.MUCD MU,
O.SMUCD SMU,
O.BUName,
O.OUName,
O.MUName,
O.SMUName,
O.UserDefSLHierarchy1 ServiceLine,
O.UserDefSLHierarchy2 SubSL1,
O.UserDefSLHierarchy3 SubSL2,
O.AlternateServiceLine,
O.UserDefAreaHierarchy1 BULevel1,
O.UserDefAreaHierarchy2 BULevel2,
O.UserDefAreaHierarchy3 BULevel3,
L.Location LocationCode,
L.City LocationCity,
L.State LocationStateProv,
L.Country LocationCountry,
L.UserDefinedHRGeo1 GeoLevel1,
L.UserDefinedHRGeo2 GeoLevel2,
L.UserDefinedHRGeo3 GeoLevel3,
L.UserDefinedHRGeo4 GeoLevel4,
L.UserDefinedHRGeo5 GeoLevel5,
E.CounselorGUI,--NEW
E.CounselorName,--NEW
E.BillRate,
E.Source,
--**** confidential fields ****
E.GenderCode,
E.TermCD TermCode,
E.TerminationReasonCode,
E.CompensationCurrency,
E.CompensationRate,
E.CompensationFrequency,
E.MonthlyCompensationRate,
E.AnnualCompensationRate,
CASE WHEN YEAR(P.SalaryEffectiveDT) > 2100 THEN NULL ELSE P.SalaryEffectiveDT END SalaryEffectiveDate,
E.SalaryAdminPlanCode,
E.SalaryAdminPlan,
E.SalaryGrade,
CASE WHEN YEAR(E.SalaryGradeEntryDate) > 2100 THEN NULL ELSE E.SalaryGradeEntryDate END SalaryGradeEntryDate,
NULL JobKEY,
NULL RowOrder
FROM dbo.vwRptFactEmployee F WITH (NOLOCK)
INNER JOIN dbo.vwRptDimEmployee E WITH (NOLOCK) ON (F.DimEmployeeKey = E.DimEmployeeKey)
INNER JOIN dbo.vwRptDimRank R WITH (NOLOCK) ON (F.DimRankKey = R.DimRankKey)
INNER JOIN dbo.vwRptDimOrganization O WITH (NOLOCK) ON (F.DimOrganizationKey = O.DimOrganizationKey)
INNER JOIN dbo.vwRptDimLocation L WITH (NOLOCK) ON (F.DimLocationKey = L.DimLocationKey)
INNER JOIN dbo.vwRptDimAssignment A WITH (NOLOCK) ON (F.DimAssignmentKey = A.DimAssignmentKey)
--INNER JOIN dbo.vwRptDimDate D WITH (NOLOCK) ON (F.TransEffectiveDateKey = D.DimDateKey)
INNER JOIN dbo.vwRptDimEmployeeV2 P WITH (NOLOCK) ON (F.DimEmployeeKey = P.DimEmployeeKey)
LEFT OUTER JOIN (SELECT ActionCode, ActionReasonCode, Description, row_number() over (partition by ActionCode, ActionReasonCode order by EffectiveDate DESC) as RowOrder
FROM PISupport.vwRptSetfActionReason WITH (NOLOCK)) AR
ON (AR.ActionCode = E.ActionCode AND AR.ActionReasonCode = E.ActionReasonCode AND AR.RowOrder = 1)
LEFT OUTER JOIN (SELECT DISTINCT C1.*, ROW_NUMBER() OVER (PARTITION BY CompanyCode ORDER BY EffectiveDate DESC) as RowOrder
FROM PISupport.vwRptSetfCompany C1 WITH (NOLOCK)) C
ON (C.CompanyCode = E.CompanyCode AND C.RowOrder = 1)
WHERE (E.JobEffectiveDT BETWEEN #JobStartDate AND #JobEndDate)
-- AND (E.ActionCode in ('ADD','DTA','HIR','POI','REH','PER','TER'))
--AND (O.BUCD+O.OUCD+O.MUCD+O.SMUCD LIKE '%'+#CodeBlock+'%' OR #CodeBlock IS NULL)
--AND (E.GPN = #GPN OR #GPN IS NULL)
--AND (E.GUI = #GUI OR #GUI IS NULL)
--AND (L.UserDefinedHRGeo1 in (#GeoArea) )
AND (L.UserDefinedHRGeo2 in ('UK and Ireland'))
--AND (L.UserDefinedHRGeo3 in (#Country) )
--AND (O.UserDefAreaHierarchy1 in (#Area) )
--AND (O.UserDefAreaHierarchy2 in (#Region) )
--AND (O.UserDefSLHierarchy1 in (#ServiceLine) )
--AND (O.UserDefSLHierarchy2 in (#SubServiceLine) )
--AND (R.RankCD in (#RankCode) )
UNION
SELECT DISTINCT * FROM (
SELECT DISTINCT
ISNULL(E.LastName,N.LastName) LastName,
ISNULL(E.SecondLastName,N.SecondLastName) SecondLastName,
ISNULL(E.FirstName,N.FirstName) FirstName,
ISNULL(E.MiddleName,N.MiddleName) MiddleName,
E.PreferredName,
ISNULL(E.PreferredFirstName,N.PreferredFirstName) PreferredFirstName,
ISNULL(E.NameAC,N.NameAlternateCharacter) NameAC,
E.LastNameAC,
E.FirstNameAC,
E.MiddleNameAC,
E.GUI,
FD.EmployeeID,
FD.LPN,
FD.GPN,
FD.EmployeeRecord,
FD.JobEffectiveDate,
FD.JobEffectiveDateSequence,
FD.ActionCode,
FD.Action,
FD.ActionDate,
FD.ActionReasonCode,
FD.ActionReason,
FD.EmployeeStatusCode,
FD.EmployeeStatus,
NULL LeaveEffectiveDate,
CASE WHEN YEAR(FD.ExpectedReturnDate) > 2100 THEN NULL ELSE FD.ExpectedReturnDate END ExpectedReturnDate,
FD.FullPartTime,
FD.ShiftCode FWACode,
FD.Shift FWAName,
NULL Telework,
FD.StandardHoursFrequency,
NULL StandardHours,
FD.FTE,
FD.PaidFTE,
NULL OvertimeEligibility,
FD.EmployeeClassCode,
FD.EmployeeClass,
FD.RegularVersusTemporary RegularTemporary,
FD.EmployeeType,
NULL PersonnelStatusDesc,
FD.PersonOrganizationRelationshipCode,
NULL PersonOfInterest,
NULL PersonOfInterestDesc,
FD.PaygroupCode,
FD.EmployeeCategoryCode,
FD.EmployeeSubcategoryCode,
NULL EmploymentCategory,
NULL NonEmployeeNonWorkTypeCode,
NULL NonEmployeeNonWorkTypeDesc,
NULL GlobalAssignmentProgramCode,
NULL GlobalAssignmentProgramDesc,
NULL GlobalAssignmentStartDate,
NULL GlobalAssignmentEndDate,
NULL InPatExPatStatus,
NULL HomeCountry,
NULL HostCountry,
NULL EYStartDate,
NULL LastRehireDate,
NULL SeniorityDate,
NULL CurrentEmploymentDate,
NULL PartnerAdmissionDate,
R.RankCDName RankCodeName,
FD.Rank,
R.RankDesc,
FD.BusinessTitle,--NEW
R.RankGroup1,--NEW
FD.GFISRank,
NULL ExperienceLevel,
NULL GlobalGrade,
FD.JobCode,--NEW
NULL JobCodeDesc,--NEW
FD.DepartmentCode,
NULL DepartmentName,
FD.CompanyCode,
C.Description Company,
C.DescrAc CompanyAC,
NULL ManagerialCountry,
O.CodeBlock,
O.BUCD BU,
O.OUCD OU,
O.MUCD MU,
O.SMUCD SMU,
O.BUName,
O.OUName,
O.MUName,
O.SMUName,
O.UserDefSLHierarchy1 ServiceLine,
O.UserDefSLHierarchy2 SubSL1,
O.UserDefSLHierarchy3 SubSL2,
O.AlternateServiceLine,
O.UserDefAreaHierarchy1 BULevel1,
O.UserDefAreaHierarchy2 BULevel2,
O.UserDefAreaHierarchy3 BULevel3,
L.Location LocationCode,
L.City LocationCity,
L.State LocationStateProv,
L.Country LocationCountry,
L.UserDefinedHRGeo1 GeoLevel1,
L.UserDefinedHRGeo2 GeoLevel2,
L.UserDefinedHRGeo3 GeoLevel3,
L.UserDefinedHRGeo4 GeoLevel4,
L.UserDefinedHRGeo5 GeoLevel5,
NULL CounselorGUI,--NEW
NULL CounselorName,--NEW
NULL BillRate,
FD.Source,
--**** confidential fields ****
NULL GenderCode,
NULL TermCode,
FD.TerminationReasonCode,
FD.CompensationCurrency,
FD.CompensationRate,
FD.CompensationFrequency,
FD.MonthlyCompensationRate,
FD.AnnualCompensationRate,
NULL SalaryEffectiveDate,
FD.SalaryAdminPlanCode,
FD.SalaryAdminPlan,
FD.SalaryGrade,
CASE WHEN YEAR(FD.SalaryGradeEntryDate) > 2100 THEN NULL ELSE FD.SalaryGradeEntryDate END SalaryGradeEntryDate,
FD.Job_KEY,
row_number() over (partition by FD.EmployeeID, FD.EmployeeRecord, FD.JobEffectiveDate,
FD.JobEffectiveDateSequence, FD.ActionCode, FD.ActionReasonCode order by FD.Job_KEY DESC) as RowOrder
FROM dbo.vwRptDimEmployee_FutureDated FD
INNER JOIN dbo.vwRptDimOrganization O WITH (NOLOCK) ON (FD.DimOrganizationKey = O.DimOrganizationKey)
INNER JOIN dbo.vwRptDimLocation L WITH (NOLOCK) ON (FD.DimLocationKey = L.DimLocationKey)
LEFT OUTER JOIN dbo.vwRptDimRank R WITH (NOLOCK) ON (FD.Rank = R.RankCD)
LEFT OUTER JOIN dbo.vwRptDimEmployeeAll E WITH (NOLOCK) ON (FD.GPN = E.GPN AND FD.GPN <> '' AND E.RowIsCurrent = 'Y')
LEFT OUTER JOIN (SELECT *, ROW_NUMBER() OVER (PARTITION BY EmployeeID, NameType ORDER BY EffectiveDate DESC) AS RowOrder
FROM PISupport.vwRptPersonACNames WITH (NOLOCK)
) N ON (N.EmployeeID = FD.EmployeeID AND N.NameType = 'PRI' AND N.CountryNameFormat = FD.SetIDLaborAgreement AND N.RowOrder = 1)
LEFT OUTER JOIN (SELECT DISTINCT C1.*, ROW_NUMBER() OVER (PARTITION BY CompanyCode ORDER BY EffectiveDate DESC) as RowOrder
FROM PISupport.vwRptSetfCompany C1 WITH (NOLOCK)) C
ON (C.CompanyCode = FD.CompanyCode AND C.RowOrder = 1)
WHERE
FD.JobEffectiveDate BETWEEN #JobStartDate AND #JobEndDate
AND FD.EDWIsCurrentRecord = 1
AND FD.EmployeeID IS NOT NULL
--AND (E.ActionCode in ('ADD','DTA','HIR','POI','REH','PER','TER'))
--AND (O.BUCD+O.OUCD+O.MUCD+O.SMUCD LIKE '%'+#CodeBlock+'%' OR #CodeBlock IS NULL)
--AND (FD.GPN = #GPN OR #GPN IS NULL)
--AND (L.UserDefinedHRGeo1 in (#GeoArea) )
AND (L.UserDefinedHRGeo2 in ('UK and Ireland'))
--AND (L.UserDefinedHRGeo3 in (#Country) )
--AND (O.UserDefAreaHierarchy1 in (#Area) )
--AND (O.UserDefAreaHierarchy2 in (#Region) )
--AND (O.UserDefSLHierarchy1 in (#ServiceLine) )
--AND (O.UserDefSLHierarchy2 in (#SubServiceLine) )
--AND (FD.Rank in (#RankCode) )
AND FD.FutureDatedEmployeeRecordsKey NOT IN (SELECT FutureDatedEmployeeRecordsKey FROM #FutureDatedExclude)
) X
WHERE RowOrder = 1
DROP TABLE #FutureDatedExclude
You most likely ran this code before you added the DROP TABLE at the bottom of your code. Therefore, the table is created and yet to be dropped. Instead of dropping it at the end, or in addition to dropping it if you want, place this at the very top of your script:
IF OBJECT_ID('tempdb..#FutureDatedExclude') IS NOT NULL DROP TABLE #FutureDatedExclude
How can I modify this query to return results that exclude all records that have a duplicate DocNum?
SELECT IdEntry, DocNum, CardCode, QUOTENAME(CardName,'"'),
Convert(Decimal(10,2),PayAmount), Convert(Decimal(10,2),InvPayAmnt),
CONVERT(VARCHAR(10), T5.PmntDate,101), NumAtCard, PymMeth, ObjType
FROM DELAWARE.dbo.PWZ3
INNER JOIN OPWZ T5 ON T5.IdNumber = IdEntry
WHERE T5.PmntDate = '3/10/2011'
AND T5.Canceled = 'N'
AND Checked = 'Y'
Try
WITH
dups (DocNum)
AS (
SELECT DocNum
FROM DELAWARE.dbo.PWZ3
GROUP BY DocNum
HAVING COUNT(1) > 1
)
SELECT PWZ3.IdEntry, PWZ3.DocNum, PWZ3.CardCode, QUOTENAME(CardName,'"'),
Convert(Decimal(10,2),PayAmount), Convert(Decimal(10,2),InvPayAmnt),
CONVERT(VARCHAR(10), T5.PmntDate,101), NumAtCard, PymMeth, ObjType
FROM DELAWARE.dbo.PWZ3 PWZ3
INNER JOIN OPWZ T5 ON T5.IdNumber = PWZ3.IdEntry
LEFT JOIN Dups ON DUPS.DocNum = PWZ3.DocNum
WHERE T5.PmntDate = '3/10/2011'
AND T5.Canceled = 'N'
AND Checked = 'Y'
AND Dups.DocNum is null
(I might not have all the column aliases right)
I'm not sure I understood all the query, but doesn't a simple
SELECT ... GROUP BY docNum
suffice?
SELECT IdEntry, DocNum, CardCode, QUOTENAME(CardName,'"'),
Convert(Decimal(10,2),PayAmount), Convert(Decimal(10,2),InvPayAmnt),
CONVERT(VARCHAR(10), T5.PmntDate,101), NumAtCard, PymMeth, ObjType
FROM DELAWARE.dbo.PWZ3
INNER JOIN OPWZ T5 ON T5.IdNumber = IdEntry
JOIN (SELECT min(IdEntry) as minIdEntry from DELAWARE.dbo.PWZ3 group by DocNum) tmp on DELAWARE.dbo.PWZ3.IdEntry = minIdEntry
WHERE T5.PmntDate = '3/10/2011'
AND T5.Canceled = 'N'
AND Checked = 'Y'