'SQL Statements to Pivot Multiple Notes into One Record
I am working on an old system that stored notes in a unique format. There are two formats the notes come in.
- A automatic date/time note followed with one or more records that contain the actual note(s)
- The first 10 characters of the note is a date with the rest being the actual note.
I would like SQL Statements that will place the logical notes into one record per note. Feel free to use multiple statements along with a Temp table to make easier to read. My initial thought it would be two statements with some sort of ROW_NUMBER and a PIVOT. I could not figure out how to do the ROW_NUMBER and if that is even what should be used.
Here is code to create the sample data:
DROP TABLE #Temp
CREATE TABLE #Temp
(
ESSN CHAR(9)
,SEQ CHAR(2)
,PGNUM DECIMAL(2)
,PGCNT DECIMAL(2)
,NOTE VARCHAR(78)
)
INSERT INTO #Temp
VALUES
('004907258','02',2,1,'|> Notes added 06/26/2017 @ 10:37 am '),
('004907258','02',2,2,'Sample note 1'),
('004907258','02',2,3,'Sample note 2'),
('004907258','02',2,4,'Sample note 3'),
('004907258','02',2,5,'|> Notes added 02/28/2018 @ 4:38 pm '),
('004907258','02',2,6,'Sample note 1'),
('004907258','02',2,7,'|> Notes added 02/28/2018 @ 4:42 pm '),
('004907258','02',2,8,'Sample note 1'),
('004907258','03',1,1,'|> Notes added 02/18/21 @ 8:57 am'),
('004907258','03',1,2,'Sample note 1'),
('004907258','03',1,3,'Sample note 2'),
('004907258','03',1,4,'|> Notes added 02/23/21 @ 7:30 pm '),
('004907258','03',1,5,'Sample note 1'),
('004907258','03',1,6,'Sample note 2'),
('004907258','03',1,7,'|> Notes added 04/30/21 @ 10:05 am '),
('004907258','03',1,8,'Sample note 1'),
('004907258','03',1,9,'Sample note 2'),
('007389511','01',1,1,'01/02/2018 Sample note 1'),
('007389511','01',1,2,'01/23/2018 Sample note 1'),
('026549779','02',1,1,'06/08/2020 Sample note 1')
SELECT * FROM #Temp
Here is some sample data as an image. The blue highlight was added to make it easier to see where the logical notes begins.
I would like a NOTECNT field added.
This will group the Notes into a Logical Note.
The Order By is ESSN, SEQ, PGNUM, PGCNT
The NOTECNT will be a sequential number and reset to 1 when
NOTE LIKE '|> %'
or
NOTE LIKE '[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9] %'
(This is the Date Logic.)
Finally, the Logical Notes will be PIVOT into one record.
Allow for up to 25 notes (NOTE1 through NOTE25)
PGNUM and PGCNT is in the sample which is only used to keep the notes in the order they were entered (ESSN, SEQ, PGNUM, PGCNT). PGNUM and PGCNT can be replaced with a Sequential number if that is easier to do.
I am using SQL Server 2008 R2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|


