DEV Community

Judy
Judy

Posted on

3 2 1 2 2

Convert cross cell to row header, row header to column:From SQL to SPL

A table in the SQL Server database can be seen as a cross table, where the combination of the first two field values can be seen as a row header, and the last three field names can be seen as column headers, where the content and quantity of the row headers are uncertain.

Image description
Now we need to convert the table into a new cross table, where the original cross cells are converted into new row headers, the original row headers are converted into column headers, and the original column headers EnteredOn, PickedTime, and DeliveredTime are replaced with the strings ENTERED, PICKED, DELIVERED.

Image description
Dynamic SQL:

Declare @SQL varchar(max) = (
Select string_agg(col,',') 
 From  (Select distinct id,Col = quotename(concat(PartNum,'_',ID)) 
         From YourTable
        )  A
)

Set @SQL = ' 
Select *
 From  (
         Select Item = concat(PartNum,''_'',ID)
               ,B.* 
          From  YourTable A
          CROSS APPLY (VALUES (EnteredOn,''ENTERED'')
                             ,(PickedTime,''PICKED'')
                             ,(DeliveredTime,''DELIVERED'')
                       ) B(t_stamp,[Status])
       ) src
 Pivot ( max(Status) for Item in ('+ @SQL +') ) pvt
 Where t_stamp is not null
Exec(@SQL)


Enter fullscreen mode Exit fullscreen mode

Ordinary SQL has a pivot function for row column conversion, but column names must be written, which requires changing the code structure. First, use stored procedures or dynamic SQL to generate column names, and then spell out SQL. The code is very complex.

SPL code is much simpler and easier to understand: try.DEMO

Image description
A1: Load data and concatenate the values of the first two fields.

A2, A4: Use pivot@r to convert columns to rows, and use pivot to convert rows to columns without writing column names.

SPL is open source free, open source address

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay