TSQL PIVOT is throwing multi-part identifier could not be bound - tsql

I've created a stored procedure in SQL Server 2005 with the following syntax:
SELECT [Encounter Number], [AdmitDate - CCYYMMDD], [DischargeDate - CCYYMMDD],
Encounter.LengthOfStay
,pr.[1] as Proc1
,pr.[2] as Proc2
,pr.[3] as Proc3
,pr.[4] as Proc4
,pr.[5] as Proc5
,pr.[6] as Proc6
,pr.[7] as Proc7
,pr.[8] as Proc8
,pr.[9] as Proc9
,pr.[10] as Proc10
,pr.[11] as Proc11
,pr.[12] as Proc12
,pr.[13] as Proc13
,pr.[14] as Proc14
,pr.[15] as Proc15
,pr.[16] as Proc16
,pr.[17] as Proc17
,pr.[18] as Proc18
,pr.[19] as Proc19
,pr.[20] as Proc20
,pr.[21] as Proc21
,pr.[22] as Proc22
,pr.[23] as Proc23
,pr.[24] as Proc24
,pr.[25] as Proc25
,pr.[26] as Proc26
,pr.[27] as Proc27
,pr.[28] as Proc28
,pr.[29] as Proc29
,pr.[30] as Proc30
,pr.[31] as Proc31
,pr.[32] as Proc32
,pr.[33] as Proc33
,pr.[34] as Proc34
,pr.[35] as Proc35
,pr.[36] as Proc36
,pr.[37] as Proc37
,pr.[38] as Proc38
,pr.[39] as Proc39
,pr.[40] as Proc40
,pr.[41] as Proc41
,pr.[42] as Proc42
,pr.[43] as Proc43
,pr.[44] as Proc44
,pr.[45] as Proc45
,pr.[46] as Proc46
,pr.[47] as Proc47
,pr.[48] as Proc48
,pr.[49] as Proc49,
CASE
WHEN [Procedure Code (ENCTR)] in ('01.25','01.14','01.59') then 'Brain'
WHEN [Procedure Code (ENCTR)] = '03.09' then 'Spinal Canal'
WHEN [Procedure Code (ENCTR)] in ('06.4','06.81','26.32') then 'Head/Neck'
WHEN [Procedure Code (ENCTR)] in ('32.29','32.39','32.49','32.59') then 'Lungs/Thorax'
WHEN [Procedure Code (ENCTR)] in ('35.12','35.21','35.22','35.23','35.24') then 'Cardiac Valve'
WHEN [Procedure Code (ENCTR)] = '36.10' then 'CABG'
WHEN [Procedure Code (ENCTR)] = '00.66' then 'PCI'
WHEN [Procedure Code (ENCTR)] in ('37.33','37.34','37.35','37.36','37.37') then 'Excision Heart
Lesion'
WHEN [Procedure Code (ENCTR)] = '37.94' then 'Implant Auto Cardioversion/Defib System'
WHEN [Procedure Code (ENCTR)] in ('39.52','39.71','39.78') then 'Abdominal Aortic Aneurysm'
WHEN [Procedure Code (ENCTR)] in ('39.50','39.79','39.72','39.74','39.75','39.76','00.62')
then 'Other Vascular'
WHEN [Procedure Code (ENCTR)] = '38.12' then 'Carotid Endarterectomy'
WHEN [Procedure Code (ENCTR)] in ('38.18','39.29') then 'Lower Limb Vascular'
WHEN [Procedure Code (ENCTR)] in ('38.34','38.44','38.45','39.25','39.71') then 'Other Aortic
Vascular'
WHEN [Procedure Code (ENCTR)] in ('44.38','44.95','44.67') then 'Other Gastrointestinal'
WHEN [Procedure Code (ENCTR)] in
('45.71','45.72','45.73','45.74','45.76','45.77','45.78','45.79','45.81','45.82','45.83','45.41',
'45.42','45.43','45.44','45.45','45.46','45.47','45.48','45.49','48.35','48.63')
then 'Colorectal'
END as ProcGrouper
From Encounter
left outer join DimFactEncounter
on Encounter.EncounterNumber = DimFactEncounter.EncounterNumber
Left Outer JOIN ( SELECT *
FROM (SELECT [Encounter Number]
,[Procedure Code (Enctr)]
,Row_Number() OVER ( Partition By [Encounter Number] Order By [Encounter
Number], [Procedure Code (Enctr)] ) AS RowNumber
FROM EncounterProc) o
PIVOT ( MAX([Procedure Code (Enctr)] ) for RowNumber IN ( [1], [2], [3], [4], [5], [6], [7],
[8], [9], [10],[11], [12], [13], [14], [15], [16], [17], [18], [19], [20] ,[21], [22], [23], [24], [25], [26], [27], [28], [29], [30]
,[31], [32], [33], [34], [35], [36], [37], [38], [39], [40]
,[41], [42], [43], [44], [45], [46], [47], [48], [49]) ) t ) pr
on Encounter.EncounterNumber = EncounterProc.[Encounter Number]
where [Date of Service] between #StartDate and #EndDate
and Encounter.InOutCode = 'I'
and AdmitSubService <> 'SIG'
and Encounter.HSP# = 1
and Encounter.ActualTotalCharge > 0
and Encounter.Age >= 65
and Encounter.PayorGroup = 'Medicare'
and [ED Flag] is null
and [DischargeDisposition] not in ('MA', 'TA', '7Z')
and EncounterProc.[Procedure Code (ENCTR)] in
('01.25','01.14','01.59','03.09','06.4','06.81','26.32','32.29','32.39','32.49',
'32.59','35.12','35.21','35.22','35.23','35.24','36.10','00.66','37.33','37.34','37.35','37.36',
'37.37','37.94','39.52','39.71','39.78','39.50','39.79','39.72','39.74','39.75','39.76','00.62',
'38.12','38.18','39.29','38.34',
'38.44','38.45','39.25','39.71','44.38','44.95','44.67','45.71','45.72','45.73','45.74','45.75',
'45.76','45.77',
'45.78','45.79','45.81','45.82','45.83','45.41','45.42','45.43','45.44','45.45','45.46','45.47'
'45.48','45.49',
'48.35','48.63')
When I attempt to alter the stored procedure, I receive the following:
Msg 4104, Level 16, State 1, Procedure sp_sc_ConRptsSurgery, Line 16
The multi-part identifier "EncounterProc.Encounter Number" could not be bound.
What must be done to the above syntax to correct the above error?
UPDATE: I changed the left outer join to the following:
Left Outer JOIN ( SELECT *
FROM (SELECT [Encounter Number]
,[Procedure Code (Enctr)]
,Row_Number() OVER
( Partition By [Encounter Number]
Order By [EncounterNumber], [Procedure Code (Enctr)] ) AS RowNumber
FROM EncounterProc) o
PIVOT ( MAX([Procedure Code (Enctr)] ) for RowNumber IN ( [1], [2], [3], [4], [5], [6], [7], [8], [9],
[10],[11], [12], [13], [14], [15], [16], [17], [18], [19], [20]
,[21], [22], [23], [24], [25], [26], [27], [28], [29], [30]
,[31], [32], [33], [34], [35], [36], [37], [38], [39], [40]
,[41], [42], [43], [44], [45], [46], [47], [48], [49]) ) t ) pr
on Encounter.EncounterNumber = pr.[Encounter Number]
UPDATE 2: Here is the structure of the EncounterProc Table:
CREATE TABLE [dbo].[EncounterProc](
[COMPANY CODE] [varchar](5) NULL,
[ENCOUNTER NUMBER] [varchar](20) NOT NULL,
[PROCEDURE CODE (ENCTR)] [varchar](15) NOT NULL,
[DATE OF SERVICE] [varchar](8) NOT NULL,
[ENCOUNTER PROC SEQUENCE] [numeric](18, 0) NOT NULL,
[SURGERY FLAG] [varchar](1) NULL,
[ORDERING PHYSICIAN] [varchar](10) NULL,
[SURGEON] [varchar](10) NULL,
[ASSISTING SURGEON(1)] [varchar](10) NULL,
[ASSISTING SURGEON(2)] [varchar](10) NULL,
[SURGERY REASON] [varchar](10) NULL,
[ANESTHESIOLOGIST] [varchar](10) NULL,
[ANESTHESIA TYPE] [varchar](2) NULL,
[PERFUSIONIST] [varchar](10) NULL,
[NURSE ANESTHETIST] [varchar](10) NULL,
[ANESTHESIA START TIME] [varchar](6) NULL,
[ANESTHESIA STOP TIME] [varchar](6) NULL,
[SURGERY START TIME] [varchar](6) NULL,
[SURGERY STOP TIME] [varchar](6) NULL,
[ENTERED OP RM TIME] [varchar](6) NULL,
[LEFT OP RM TIME] [varchar](6) NULL,
[PACU ADMIT TIME] [varchar](6) NULL,
[PACU DISCHARGE TIME] [varchar](6) NULL,
[USER DEFINED 1] [varchar](30) NULL,
[USER DEFINED 2] [varchar](30) NULL,
[USER DEFINED 3] [varchar](30) NULL,
[USER DEFINED 4] [varchar](30) NULL,
[USER DEFINED 5] [varchar](30) NULL,
[USER DEFINED 6] [varchar](30) NULL,
[USER DEFINED 7] [varchar](30) NULL,
[USER DEFINED 8] [varchar](30) NULL,
[USER DEFINED NUMBER 1] [numeric](18, 4) NULL,
[USER DEFINED DATE 1] [varchar](8) NULL,
[PRINCIPLE SECONDARY PROC] [varchar](1) NULL,
[Updated] [datetime] NULL,
CONSTRAINT [PK_EncounterProc2] PRIMARY KEY CLUSTERED
(
[ENCOUNTER NUMBER] ASC,
[PROCEDURE CODE (ENCTR)] ASC,
[DATE OF SERVICE] ASC,
[ENCOUNTER PROC SEQUENCE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS
= ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Unforutnately, the errors are still persisting including:
Msg 207, Level 16, State 1, Procedure sp_sc_ConRptsSurgery, Line 95
Invalid column name 'EncounterNumber'.
Msg 207, Level 16, State 1, Procedure sp_sc_ConRptsSurgery, Line 103
Invalid column name 'Date of Service'.
Msg 207, Level 16, State 1, Procedure sp_sc_ConRptsSurgery, Line 103
Invalid column name 'Date of Service'.
Msg 207, Level 16, State 1, Procedure sp_sc_ConRptsSurgery, Line 112
Invalid column name 'Procedure Code (ENCTR)'.
Why are these column names deemed invalid?
Update 3:
Not sure why my question was downvoted?
After parsing thrugh the error message, I restructured the stored procedure as follows:
SELECT Encounter.EncounterNumber, [AdmitDate - CCYYMMDD], [DischargeDate - CCYYMMDD],
Encounter.LengthOfStay
,pr.[1] as Proc1
,pr.[2] as Proc2
,pr.[3] as Proc3
,pr.[4] as Proc4
,pr.[5] as Proc5
,pr.[6] as Proc6
,pr.[7] as Proc7
,pr.[8] as Proc8
,pr.[9] as Proc9
,pr.[10] as Proc10
,pr.[11] as Proc11
,pr.[12] as Proc12
,pr.[13] as Proc13
,pr.[14] as Proc14
,pr.[15] as Proc15
,pr.[16] as Proc16
,pr.[17] as Proc17
,pr.[18] as Proc18
,pr.[19] as Proc19
,pr.[20] as Proc20
,pr.[21] as Proc21
,pr.[22] as Proc22
,pr.[23] as Proc23
,pr.[24] as Proc24
,pr.[25] as Proc25
,pr.[26] as Proc26
,pr.[27] as Proc27
,pr.[28] as Proc28
,pr.[29] as Proc29
,pr.[30] as Proc30
,pr.[31] as Proc31
,pr.[32] as Proc32
,pr.[33] as Proc33
,pr.[34] as Proc34
,pr.[35] as Proc35
,pr.[36] as Proc36
,pr.[37] as Proc37
,pr.[38] as Proc38
,pr.[39] as Proc39
,pr.[40] as Proc40
,pr.[41] as Proc41
,pr.[42] as Proc42
,pr.[43] as Proc43
,pr.[44] as Proc44
,pr.[45] as Proc45
,pr.[46] as Proc46
,pr.[47] as Proc47
,pr.[48] as Proc48
,pr.[49] as Proc49,
CASE
WHEN [Procedure Code (ENCTR)] in ('01.25','01.14','01.59') then 'Brain'
WHEN [Procedure Code (ENCTR)] = '03.09' then 'Spinal Canal'
WHEN [Procedure Code (ENCTR)] in ('06.4','06.81','26.32') then 'Head/Neck'
WHEN [Procedure Code (ENCTR)] in ('32.29','32.39','32.49','32.59') then 'Lungs/Thorax'
WHEN [Procedure Code (ENCTR)] in ('35.12','35.21','35.22','35.23','35.24') then 'Cardiac Valve'
WHEN [Procedure Code (ENCTR)] = '36.10' then 'CABG'
WHEN [Procedure Code (ENCTR)] = '00.66' then 'PCI'
WHEN [Procedure Code (ENCTR)] in ('37.33','37.34','37.35','37.36','37.37') then 'Excision Heart
Lesion'
WHEN [Procedure Code (ENCTR)] = '37.94' then 'Implant Auto Cardioversion/Defib System'
WHEN [Procedure Code (ENCTR)] in ('39.52','39.71','39.78') then 'Abdominal Aortic Aneurysm'
WHEN [Procedure Code (ENCTR)] in ('39.50','39.79','39.72','39.74','39.75','39.76','00.62')
then 'Other Vascular'
WHEN [Procedure Code (ENCTR)] = '38.12' then 'Carotid Endarterectomy'
WHEN [Procedure Code (ENCTR)] in ('38.18','39.29') then 'Lower Limb Vascular'
WHEN [Procedure Code (ENCTR)] in ('38.34','38.44','38.45','39.25','39.71') then 'Other Aortic
Vascular'
WHEN [Procedure Code (ENCTR)] in ('44.38','44.95','44.67') then 'Other Gastrointestinal'
WHEN [Procedure Code (ENCTR)] in
('45.71','45.72','45.73','45.74','45.76','45.77','45.78','45.79','45.81','45.82','45.83','45.41',
'45.42','45.43','45.44','45.45','45.46','45.47','45.48','45.49','48.35','48.63')
then 'Colorectal'
END as ProcGrouper
From Encounter
left outer join DimFactEncounter
on Encounter.EncounterNumber = DimFactEncounter.EncounterNumber
Left Outer JOIN EncounterProc
on Encounter.EncounterNumber = EncounterProc.[Encounter Number]
Left Outer JOIN
(
SELECT [Encounter Number], [DATE OF SERVICE],
[1], [2], [3], [4], [5], [6], [7], [8], [9], [10],[11], [12], [13], [14], [15], [16], [17], [18],
[19], [20],[21], [22], [23], [24], [25], [26], [27], [28], [29], [30]
,[31], [32], [33], [34], [35], [36], [37], [38], [39], [40]
,[41], [42], [43], [44], [45], [46], [47], [48], [49]
FROM
(
SELECT [Encounter Number], [DATE OF SERVICE]
,[Procedure Code (Enctr)]
,Row_Number() OVER ( Partition By [Encounter Number] Order By [Encounter Number], [Procedure
Code (Enctr)] ) AS RowNumber
FROM EncounterProc
where [Procedure Code (ENCTR)] in
('01.25','01.14','01.59','03.09','06.4','06.81','26.32','32.29','32.39','32.49',
'32.59','35.12','35.21','35.22','35.23','35.24','36.10','00.66','37.33','37.34','37.35','37.36',
'37.37','37.94','39.52','39.71','39.78','39.50','39.79','39.72','39.74','39.75','39.76','00.62',
'38.12','38.18','39.29','38.34', '38.44','38.45','39.25','39.71','44.38','44.95','44.67','45.71','45.72','45.73','45.74','45.75',
'45.76','45.77', '45.78','45.79','45.81','45.82','45.83','45.41','45.42','45.43','45.44','45.45',
'45.46','45.47','45.48','45.49', '48.35','48.63')
) o
PIVOT
(
MAX([Procedure Code (Enctr)])
for RowNumber IN ( [1], [2], [3], [4], [5], [6], [7], [8], [9], [10],[11], [12], [13], [14],[15],
[16], [17], [18], [19], [20],[21], [22], [23], [24], [25], [26], [27], [28], [29], [30]
,[31], [32], [33], [34], [35], [36], [37], [38], [39], [40]
,[41], [42], [43], [44], [45], [46], [47], [48], [49])
) t
) pr
on pr.[Encounter Number] = Encounter.EncounterNumber
where pr.[Date of Service] between #StartDate and #EndDate
and Encounter.InOutCode = 'I'
and AdmitSubService <> 'SIG'
and Encounter.HSP# = 1
and Encounter.ActualTotalCharge > 0
and Encounter.Age >= 65
and Encounter.PayorGroup = 'Medicare'
and [ED Flag] is null
and [DischargeDisposition] not in ('MA', 'TA', '7Z')
The stored procedure runs error free now. However, I'm seeing the same encounter number duplicated for however many rows as it has procedures. If there are 7 procedures, the stored procedure returns 7 rows for this encounter.
How would I modify the updated code above to ensure only one row per encounter is returned by the stored procedure?

I believe the error is at the end of your PIVOT:
) pr
on Encounter.EncounterNumber = EncounterProc.[Encounter Number]
^-- this should be pr
So the code should be:
) pr
on Encounter.EncounterNumber = pr.[Encounter Number]
Edit, based on your additional errors, it appears that you are not including the [DATE OF SERVICE] in your subquery. Also it doesn't make sense that you have a filter on the outside WHERE clause using the [Procedure Code (ENCTR)] because you are using that column in your max() on the PIVOT. Based on those guesses your code seems like it should be:
SELECT [Encounter Number], [AdmitDate - CCYYMMDD], [DischargeDate - CCYYMMDD],
Encounter.LengthOfStay
,pr.[1] as Proc1
,pr.[2] as Proc2
,pr.[3] as Proc3
,pr.[4] as Proc4
,pr.[5] as Proc5
,pr.[6] as Proc6
,pr.[7] as Proc7
,pr.[8] as Proc8
,pr.[9] as Proc9
,pr.[10] as Proc10
,pr.[11] as Proc11
,pr.[12] as Proc12
,pr.[13] as Proc13
,pr.[14] as Proc14
,pr.[15] as Proc15
,pr.[16] as Proc16
,pr.[17] as Proc17
,pr.[18] as Proc18
,pr.[19] as Proc19
,pr.[20] as Proc20
,pr.[21] as Proc21
,pr.[22] as Proc22
,pr.[23] as Proc23
,pr.[24] as Proc24
,pr.[25] as Proc25
,pr.[26] as Proc26
,pr.[27] as Proc27
,pr.[28] as Proc28
,pr.[29] as Proc29
,pr.[30] as Proc30
,pr.[31] as Proc31
,pr.[32] as Proc32
,pr.[33] as Proc33
,pr.[34] as Proc34
,pr.[35] as Proc35
,pr.[36] as Proc36
,pr.[37] as Proc37
,pr.[38] as Proc38
,pr.[39] as Proc39
,pr.[40] as Proc40
,pr.[41] as Proc41
,pr.[42] as Proc42
,pr.[43] as Proc43
,pr.[44] as Proc44
,pr.[45] as Proc45
,pr.[46] as Proc46
,pr.[47] as Proc47
,pr.[48] as Proc48
,pr.[49] as Proc49,
CASE
WHEN [Procedure Code (ENCTR)] in ('01.25','01.14','01.59') then 'Brain'
WHEN [Procedure Code (ENCTR)] = '03.09' then 'Spinal Canal'
WHEN [Procedure Code (ENCTR)] in ('06.4','06.81','26.32') then 'Head/Neck'
WHEN [Procedure Code (ENCTR)] in ('32.29','32.39','32.49','32.59') then 'Lungs/Thorax'
WHEN [Procedure Code (ENCTR)] in ('35.12','35.21','35.22','35.23','35.24') then 'Cardiac Valve'
WHEN [Procedure Code (ENCTR)] = '36.10' then 'CABG'
WHEN [Procedure Code (ENCTR)] = '00.66' then 'PCI'
WHEN [Procedure Code (ENCTR)] in ('37.33','37.34','37.35','37.36','37.37') then 'Excision Heart
Lesion'
WHEN [Procedure Code (ENCTR)] = '37.94' then 'Implant Auto Cardioversion/Defib System'
WHEN [Procedure Code (ENCTR)] in ('39.52','39.71','39.78') then 'Abdominal Aortic Aneurysm'
WHEN [Procedure Code (ENCTR)] in ('39.50','39.79','39.72','39.74','39.75','39.76','00.62')
then 'Other Vascular'
WHEN [Procedure Code (ENCTR)] = '38.12' then 'Carotid Endarterectomy'
WHEN [Procedure Code (ENCTR)] in ('38.18','39.29') then 'Lower Limb Vascular'
WHEN [Procedure Code (ENCTR)] in ('38.34','38.44','38.45','39.25','39.71') then 'Other Aortic
Vascular'
WHEN [Procedure Code (ENCTR)] in ('44.38','44.95','44.67') then 'Other Gastrointestinal'
WHEN [Procedure Code (ENCTR)] in
('45.71','45.72','45.73','45.74','45.76','45.77','45.78','45.79','45.81','45.82','45.83','45.41',
'45.42','45.43','45.44','45.45','45.46','45.47','45.48','45.49','48.35','48.63')
then 'Colorectal'
END as ProcGrouper
From Encounter
left outer join DimFactEncounter
on Encounter.EncounterNumber = DimFactEncounter.EncounterNumber
Left Outer JOIN
(
SELECT [Encounter Number], [DATE OF SERVICE],
[1], [2], [3], [4], [5], [6], [7], [8], [9], [10],[11], [12], [13], [14], [15], [16], [17], [18], [19], [20] ,[21], [22], [23], [24], [25], [26], [27], [28], [29], [30]
,[31], [32], [33], [34], [35], [36], [37], [38], [39], [40]
,[41], [42], [43], [44], [45], [46], [47], [48], [49]
FROM
(
SELECT [Encounter Number], [DATE OF SERVICE]
,[Procedure Code (Enctr)]
,Row_Number() OVER ( Partition By [Encounter Number] Order By [Encounter
Number], [Procedure Code (Enctr)] ) AS RowNumber
FROM EncounterProc
where [Procedure Code (ENCTR)] in
('01.25','01.14','01.59','03.09','06.4','06.81','26.32','32.29','32.39','32.49',
'32.59','35.12','35.21','35.22','35.23','35.24','36.10','00.66','37.33','37.34','37.35','37.36',
'37.37','37.94','39.52','39.71','39.78','39.50','39.79','39.72','39.74','39.75','39.76','00.62',
'38.12','38.18','39.29','38.34', '38.44','38.45','39.25','39.71','44.38','44.95','44.67','45.71','45.72','45.73','45.74','45.75',
'45.76','45.77', '45.78','45.79','45.81','45.82','45.83','45.41','45.42','45.43','45.44','45.45','45.46','45.47'
'45.48','45.49', '48.35','48.63')
) o
PIVOT
(
MAX([Procedure Code (Enctr)])
for RowNumber IN ( [1], [2], [3], [4], [5], [6], [7], [8], [9], [10],[11], [12], [13], [14], [15], [16], [17], [18], [19], [20] ,[21], [22], [23], [24], [25], [26], [27], [28], [29], [30]
,[31], [32], [33], [34], [35], [36], [37], [38], [39], [40]
,[41], [42], [43], [44], [45], [46], [47], [48], [49])
) t
) pr
on Encounter.EncounterNumber = pr.[Encounter Number]
where pr.[Date of Service] between #StartDate and #EndDate
and Encounter.InOutCode = 'I'
and AdmitSubService <> 'SIG'
and Encounter.HSP# = 1
and Encounter.ActualTotalCharge > 0
and Encounter.Age >= 65
and Encounter.PayorGroup = 'Medicare'
and [ED Flag] is null
and [DischargeDisposition] not in ('MA', 'TA', '7Z')

Related

Error converting data type nvarchar to datetime2 . The incorrect value "1" is supplied in the PIVOT operator

I thought the brackets indicate the header of the pivot table. Can you explain why I am getting a data type error?
SELECT *
FROM (SELECT TLInstance, Data, RPTMth
FROM dbo.VIEW_MeterData) p
PIVOT (max(Data)
FOR RPTMth IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])
) AS MeterDataPivot
In View_MeterData I had to add "MONTH" to this code.
SELECT TOP (100) PERCENT TLInstance, Data, MONTH(DATEADD(MONTH, - 1, Timestamp)) AS RPTMth, Timestamp
FROM dbo.VIEW_TLData

Need to Pull result from last year into inventory usage report

I have an inventory usage report that pulls in transactions from the previous year. Right now I have results for the current year. What is the correct date syntax for me to use?
Below is what I have currently for this year I am using the get date function for this year and need it to calculate the same information, but break it down monthly for last year.
SELECT OITM.ItemCode, OITM.ItemName AS 'Description', OITM.CardCode AS
'Vendor',
SUM(OITW.OnHand) AS 'On Hand', SUM(OITW.OnOrder) AS 'On Order',
SUM(OITW.IsCommited) AS 'Committed',
(SUM(OITW.OnHand)+SUM(OITW.OnOrder)-SUM(OITW.IsCommited)) AS 'Available',
OITM.AvgPrice AS 'Unit Cost',(SUM(OITW.OnHand)*OITM.AvgPrice) AS 'Value $',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
YEAR(OINM.DocDate)=((year, -1, GETDATE()) AND OINM.ItemCode = OITM.ItemCode
GROUP BY
OINM.ItemCode) AS 'Prev. Year',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='1' AND YEAR(OINM.DocDate)=(year, -1, GETDATE()) AND
OINM.ItemCode =
OITM.ItemCode GROUP BY OINM.ItemCode) AS 'JAN',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='2' AND YEAR(OINM.DocDate)=(year, -1, GETDATE()) AND
OINM.ItemCode =
OITM.ItemCode GROUP BY OINM.ItemCode) AS 'FEB',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='3' AND YEAR(OINM.DocDate)=YEAR(getdate()) AND
OINM.ItemCode =
OITM.ItemCode GROUP BY OINM.ItemCode) AS 'MAR',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='4' AND YEAR(OINM.DocDate)=YEAR(getdate()) AND
OINM.ItemCode =
OITM.ItemCode GROUP BY OINM.ItemCode) AS 'APR',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='5' AND YEAR(OINM.DocDate)=YEAR(getdate()) AND
OINM.ItemCode =
OITM.ItemCode GROUP BY OINM.ItemCode) AS 'MAY',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='6' AND YEAR(OINM.DocDate)=YEAR(getdate()) AND
OINM.ItemCode =
OITM.ItemCode GROUP BY OINM.ItemCode) AS 'JUN',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='7' AND YEAR(OINM.DocDate)=YEAR(getdate()) AND
OINM.ItemCode =
OITM.ItemCode GROUP BY OINM.ItemCode) AS 'JUL',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='8' AND YEAR(OINM.DocDate)=YEAR(getdate()) AND
OINM.ItemCode =
OITM.ItemCode GROUP BY OINM.ItemCode) AS 'AUG',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='9' AND YEAR(OINM.DocDate)=YEAR(getdate()) AND
OINM.ItemCode =
OITM.ItemCode GROUP BY OINM.ItemCode) AS 'SEP',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='10' AND YEAR(OINM.DocDate)=YEAR(getdate()) AND
OINM.ItemCode =
OITM.ItemCode GROUP BY OINM.ItemCode) AS 'OCT',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='11' AND YEAR(OINM.DocDate)=YEAR(getdate()) AND
OINM.ItemCode =
OITM.ItemCode GROUP BY OINM.ItemCode) AS 'NOV',
(SELECT SUM(OINM.OutQty) FROM OINM WHERE OINM.TransType <> '67' AND
MONTH(OINM.DocDate)='12' AND YEAR(OINM.DocDate)=YEAR(getdate()) AND
OINM.ItemCode =
OITM.ItemCode GROUP BY OINM.ItemCode) AS 'DEC'
FROM OITM, OITW
WHERE OITM.ItemCode=OITW.ItemCode
My suggestion is to shorten the original query a bit. If I'm not completely wrong, it can be written as follows:
WITH
OINM_Base (ItemCode, [Month], OutQty) AS (
SELECT
ItemCode,
CASE GROUPING(MONTH(DocDate))
WHEN 1 THEN 0 ELSE MONTH(DocDate)
END,
SUM(OutQty)
FROM OINM
WHERE TransType <> '67' AND YEAR(DocDate) = YEAR(GETDATE()) -- change this for the previous year
GROUP BY ItemCode, ROLLUP(MONTH(DocDate))
),
OINM_Data (ItemCode, [Year], JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, [DEC]) AS (
SELECT ItemCode, [0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]
FROM OINM_Base
PIVOT (SUM(OutQty) FOR [Month] IN ([0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])) pvt
),
OITW_Data (ItemCode, [On Hand], [On Order], [Committed]) AS (
SELECT ItemCode, SUM(OnHand), SUM(OnOrder), SUM(IsCommited)
FROM OITW
GROUP BY ItemCode
)
SELECT
tm.ItemCode,
tm.ItemName AS [Description],
tm.CardCode AS Vendor,
tw.[On Hand], tw.[On Order], tw.[Committed],
tw.[On Hand] + tw.[On Order] - tw.[Committed] AS Available,
tm.AvgPrice AS [Unit Cost],
tw.[On Hand] * tm.AvgPrice AS [Value $],
nm.[Year], nm.JAN, nm.FEB, nm.MAR, nm.APR, nm.MAY, nm.JUN, nm.JUL, nm.AUG, nm.SEP, nm.OCT, nm.NOV, nm.[DEC]
FROM OITM tm
INNER JOIN OITW_Data tw ON tm.ItemCode = tw.ItemCode
LEFT OUTER JOIN OINM_Data nm ON tm.ItemCode = nm.ItemCode;
This works as follows:
The data in OINM is restricted to the year in question, summing the OutQty values per month and creating a total for the year which is labelled as month number 0 (CTE OINM_Base). Using a PIVOT query, the sums appearing on different rows are turned into columns (CTE OINM_Data). The aggregation for the OITW data is also done saparately (CTE OITW_Data).
Both OINM_Data and OITW_Data are finally joined with the data building the main rows from OITM. Here, the final calculations are done (Available and Value $).
Now, to change the query to return the previous year, only one thing has to be changed (see my comment "change this for the previous year"), namely :
YEAR(GETDATE()) has to be replaced by YEAR(GETDATE()) - 1.

T-SQL Pivot Incorrect syntax near the keyword 'FOR'

I'm working on the Datacamp T-SQL course and I can't figure out to use a pivot for some reason.
Start query is:
SELECT CategoryID, AVG(UnitPrice) AS Price
FROM Products
GROUP BY CategoryID;
Results are:
CategoryID Price
----------------------
1 37.9791
2 23.0625
3 25.1600
4 28.7300
5 20.2500
6 54.0066
7 32.3700
8 20.6825
Results I want:
Per Category 1 2 3 4 5 6 7 8
Average Unit Price 37.98 23.06 25.16 28.73 20.25 54.01 32.37 20.68
Code I wrote:
SELECT *
FROM
(SELECT CategoryID, AVG(UnitPrice)
FROM DBO.Products) AS test
PIVOT
(UnitPrice
FOR CategoryID IN ([1], [2], [3], [4], [5], [6], [7], [8])) AS PivotTable
GROUP BY
CategoryID
But then I get the error
[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near the keyword 'FOR'. (156) (SQLExecDirectW)
I also tried AVG(UnitPrice) in the pivot.
It then generated this error:
[42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'UnitPrice'. (207) (SQLExecDirectW)
I've been on this one for a while now, and I have no idea where to look. If someone could point me in the right direction, thanks in advance.
Assuming there are more columns in Products than just those shown, I think you want:
SELECT * FROM
(SELECT CategoryID, UnitPrice
FROM DBO.Products) as test
PIVOT (
AVG(UnitPrice) FOR
CategoryID IN ([1], [2], [3], [4], [5], [6], [7], [8])
) AS PivotTable
PIVOT hides an explicit grouping which we don't need to repeat. If Products only contains CategoryID and UnitPrice, we can use it directly rather than the test subquery
I would remove GROUP BY:
SELECT *
FROM (SELECT CategoryID, UnitPrice FROM DBO.Products) as test
PIVOT (AVG(UnitPrice) FOR CategoryID IN ([1], [2], [3], [4], [5], [6], [7], [8])
) AS PivotTable
SELECT CategoryID, [1], [2], [3], [4], [5], [6], [7], [8] FROM
(SELECT price, CategoryID from dbo.Products) x
PIVOT (
MAX(price) FOR
CategoryID IN ([1], [2], [3], [4], [5], [6], [7], [8])
) AS PivotTable
This works:
SELECT 'Average Unit Price' AS 'Per Category',
[1], [2], [3], [4], [5], [6], [7], [8]
FROM
(SELECT CategoryID, UnitPrice
FROM dbo.Products) AS SourceTable
PIVOT
(
AVG(UnitPrice)
FOR CategoryID IN ([1], [2], [3], [4], [5], [6], [7], [8])
) AS PivotTable;

Pulling another bit of data from delimited string for query results

I use the code below to extract a piece of data that is so many along in the delimited string after a certain character or number appears, I wish to pull another piece of data to appear before each of these values being pulled.
I do not fully understand how the code works, although I do understand elements of it. I just wish to repeat the process of pulling and integrate it into the query results.
USE RUG_Data
IF OBJECT_ID('tempdb..#splitoutdata','U') IS NOT NULL DROP TABLE #SPLITOUTDATA;
CREATE TABLE #SPLITOUTDATA (
INDEX1 INT,
ROWNUM INT,
BITOFDATA VARCHAR(max));
IF OBJECT_ID(N'dbo.Split_XML', N'TF') IS NOT NULL DROP FUNCTION dbo.Split_XML
GO
SET QUOTED_IDENTIFIER ON
SET ANSI_NULLS ON
GO
CREATE FUNCTION dbo.Split_XML
(
#Parameter VARCHAR(MAX)
,#Delimiter VARCHAR(1)
)
RETURNS #Result TABLE
(
ItemNumber INT
,ItemValue VARCHAR(MAX)
)
AS
BEGIN
DECLARE #XML XML ;
SET #Parameter = ( SELECT #Parameter
FOR XML PATH('')
) ;
SELECT #XML = '<r>' + REPLACE(#Parameter, #Delimiter, '</r><r>') + '</r>' ;
INSERT INTO #Result
(
ItemNumber
,ItemValue
)
SELECT ROW_NUMBER() OVER ( ORDER BY ( SELECT NULL) ) AS ItemNumber
, Item.value('text()[1]', 'VARCHAR(MAX)') AS ItemValue
FROM #XML.nodes('//r') R ( Item ) ;
RETURN ;
END ;
GO
;WITH
REFORMATTEDDATA AS
(
SELECT
row_number()over(order by (select null)) as INDEX1,
REPLACE(REPLACE(CAST(DATA AS VARCHAR(MAX)),CHAR(13),''),CHAR(10),'')AS RAWCLOB2
FROM
RUG_CLOB
WHERE
CAST(DATA AS VARCHAR(MAX)) LIKE 'ZHV|FS0000%%%|D0003001%'
)
INSERT INTO #SPLITOUTDATA
SELECT
INDEX1,
ROW_NUMBER()OVER(PARTITION BY INDEX1 ORDER BY split.ItemNumber) AS ROWNUM,
split.ItemValue AS BITOFDATA
FROM REFORMATTEDDATA
CROSS APPLY dbo.Split_XML(reformatteddata.RAWCLOB2,'|') SPLIT
CREATE CLUSTERED INDEX idx1 ON #SPLITOUTDATA (INDEX1,ROWNUM)
SELECT
[Date], [MPAN],
[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],
[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31],[32],[33],[34],[35],[36],[37],[38],[39],[40],[41],[42],[43],[44],[45],[46],[47],[48],[49],[50]
FROM
(
SELECT
INDEX1,
(SELECT BITOFDATA FROM #SPLITOUTDATA so2 WHERE so2.INDEX1 = so1.INDEX1 and so2.ROWNUM = 8) AS [Date] ,
(SELECT BITOFDATA FROM #SPLITOUTDATA so2 WHERE so2.INDEX1 = so1.INDEX1 and so2.ROWNUM = 14) AS [MPAN] ,
ROW_NUMBER()OVER(PARTITION BY INDEX1 ORDER BY ROWNUM) AS ROWNUM,
(SELECT BITOFDATA FROM #SPLITOUTDATA so4 WHERE so4.INDEX1 = so1.INDEX1 AND so4.ROWNUM = so1.ROWNUM +3) AS BITOFDATA
FROM #SPLITOUTDATA so1
WHERE BITOFDATA = '012'
-- AND
--(SELECT BITOFDATA FROM #SPLITOUTDATA so5 WHERE so5.DC_INDEX_FK = so1.DC_INDEX_FK AND so5.ROWNUM = 10) NOT IN ('TR01')
) p
PIVOT
(MAX (BITOFDATA)
FOR ROWNUM IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31],[32],[33],[34],[35],[36],[37],[38],[39],[40],[41],[42],[43],[44],[45],[46],[47],[48],[49],[50])
) AS PVT
IF OBJECT_ID('tempdb..#splitoutdata','U') IS NOT NULL DROP TABLE #SPLITOUTDATA;
IF OBJECT_ID(N'dbo.Split_XML', N'TF') IS NOT NULL DROP FUNCTION dbo.Split_XML
At the moment my query results show as –
[Date], [MPAN],
[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],
[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31],[32],[33],[34],[35],[36],[37],[38],[39],[40],[41],[42],[43],[44],[45],[46],[47],[48],[49],[50]
I wish to have
[Date], [MPAN],
[E/A],[1], [E/A], [2], [E/A], [3], [E/A], [4], [E/A], [5], [E/A], [6], [E/A], [7], [E/A], [8], [E/A], [9], [E/A], [10], [E/A], [11], [E/A], [12], [E/A], [13], [E/A], [14], [E/A], [15], [E/A], [16], [E/A], [17], [E/A], [18], [E/A], [19], [E/A],[20], [E/A], [21], [E/A], [22], [E/A], [23], [E/A], [24], [E/A], [25], [E/A], [26], [E/A], [27], [E/A],[28], [E/A], [29], [E/A], [30], [E/A], [31], [E/A], [32], [E/A], [33], [E/A], [34], [E/A],[35], [E/A],[36], [E/A], [37], [E/A], [38], [E/A], [39], [E/A], [40], [E/A], [41], [E/A], [42], [E/A], [43], [E/A], [44], [E/A], [45], [E/A], [46], [E/A], [47], [E/A], [48], [E/A],[49], [E/A], [50]
The E/A value is also within the delimited string and features one piece before the value I am pulling every time so I assume in some way I will use this bit of code to pull it:
(SELECT BITOFDATA FROM #SPLITOUTDATA so4 WHERE so4.INDEX1 = so1.INDEX1 AND so4.ROWNUM = so1.ROWNUM +2) AS BITOFDATA
FROM #SPLITOUTDATA so1
WHERE BITOFDATA = '012'
I just can’t get it to work for some reason as I’m fairly new at this but I assume it’s fairly simple.
Sorry if I haven't explained it very well.
It's hard to tell without sample data, but you should be able to PIVOT a second time on the results of your PIVOT to get the results you're after

TSQL Query Pivoting

I have a table strcuture (golf score card) as follow:
HoleID int
CourseID int
Par INT
Distance INT
LowIndex INT
HighIndex INT
Sequence INT (representing the sequence of the hole: 1, 2, 3, ... 18)
This course has 18 holes.
I want to pivoting into:
Hole, 1, 2, 3, ... 18
Par, X, X, X, ... X
Distance, Y, Y, Y, ... Y
LowIndex, Z, Z, Z, ... Z
HighIndex, A, A, A, ... A
I can achieve this by using cursor but is there any better way?
TSQL has direct support for pivoting. Take a look here and here, for example.
You could do
SELECT HoleID FROM Card WHERE HoleId =1 ,(SELECT HoleID FROM Card WHERE HoleId =2) , -- etc
UNION
SELECT Par FROM Card WHERE HoleId = 1, (SELECT Par FROM Card where HoleID=2). --etc
UNION
SELECT Distance FROM Card WHERE HoleId = 1, (SELECT Distance FROM Card where HoleID=2). --etc
UNION
SELECT LowIndex FROM Card WHERE HoleId = 1, (SELECT LowIndex FROM Card where HoleID=2). --etc
UNION
SELECT HIghIndex FROM Card WHERE HoleId = 1, (SELECT HighIndex FROM Card where HoleID=2). --etc
if you were desperate to get rid of the cursor.
Make sure that you make all the datatypes the same through a cast or something.
Got it the first part only ... that will do.
select [1],[2],[3],[4],[5],[6],[7],[8],[9], [10], [11], [12], [13], [14], [15], [16], [17], [18]
from (Select Sequence, Par FROM holes WHERE CourseID=1) a
PIVOT
(
Max(Par)
FOR [Sequence] IN ([1],[2],[3],[4],[5],[6],[7],[8],[9], [10], [11], [12], [13], [14], [15], [16], [17], [18])
) AS p
Complete list:
select 'Par', [1],[2],[3],[4],[5],[6],[7],[8],[9], [10], [11], [12], [13], [14], [15], [16], [17], [18]
from (Select Sequence, Par FROM holes WHERE CourseID=1) a
PIVOT
(
Max(Par)
FOR [Sequence] IN ([1],[2],[3],[4],[5],[6],[7],[8],[9], [10], [11], [12], [13], [14], [15], [16], [17], [18])
) AS p
UNION
select 'Distance', [1],[2],[3],[4],[5],[6],[7],[8],[9], [10], [11], [12], [13], [14], [15], [16], [17], [18]
from (Select Sequence, Distance FROM holes WHERE CourseID=1) a
PIVOT
(
Max(Distance)
FOR [Sequence] IN ([1],[2],[3],[4],[5],[6],[7],[8],[9], [10], [11], [12], [13], [14], [15], [16], [17], [18])
) AS p
UNION
select 'LowIndex', [1],[2],[3],[4],[5],[6],[7],[8],[9], [10], [11], [12], [13], [14], [15], [16], [17], [18]
from (Select Sequence, LowIndex FROM holes WHERE CourseID=1) a
PIVOT
(
Max(LowIndex)
FOR [Sequence] IN ([1],[2],[3],[4],[5],[6],[7],[8],[9], [10], [11], [12], [13], [14], [15], [16], [17], [18])
) AS p
UNION
select 'HighIndex', [1],[2],[3],[4],[5],[6],[7],[8],[9], [10], [11], [12], [13], [14], [15], [16], [17], [18]
from (Select Sequence, HighIndex FROM holes WHERE CourseID=1) a
PIVOT
(
Max(HighIndex)
FOR [Sequence] IN ([1],[2],[3],[4],[5],[6],[7],[8],[9], [10], [11], [12], [13], [14], [15], [16], [17], [18])
) AS p