I’m not sure how to even word/explain what I’m looking for. I have data like this:
| CODE_NBR | LIST1 | LIST2 | LIST3 | LIST4 | LIST5 | LIST6 | LIST7 | LIST8 | LIST9 |
| ------------ | ------------ | ------------ | ------------ | ------------ | ------------ | ------------ | ------------ | ------------ | ------------ |
| AA1 | L19 | L14 | L15 | L16 | | L18 | | L54 | |
| AB1 | L60 | L14 | | L16 | | L18 | | | L56 |
I want them to be put into consecutive columns like this, basically removing gaps between:
CODE_NBR | NewList1 | NewList2 | NewList3 | NewList4 | NewList5 | NewList6 | NewList7 | NewList8 | NewList9 |
---|---|---|---|---|---|---|---|---|---|
AA1 | L19 | L14 | L15 | L16 | L18 | L54 | |||
AB1 | L60 | L14 | L16 | L18 | L56 |
I've tried unpivoting the columns into one column them pivoting them back and they just go back where they were. I also tried dynamic SQL and it still put them in the same place they were originally in, so I'm not sure how I can accomplish what I'm trying to do. This is sample data
--DROP TABLE PLANS;
CREATE TABLE PLANS
(
CODE_NBR nvarchar(3),
ListTable1 nvarchar(10),
ListTable2 nvarchar(10),
ListTable3 nvarchar(10),
ListTable4 nvarchar(10),
ListTable5 nvarchar(10),
ListTable6 nvarchar(10),
ListTable7 nvarchar(10),
ListTable8 nvarchar(10),
ListTable9 nvarchar(10)
);
INSERT INTO PLANS
VALUES ('AA1','L19','L14','L15','L16','','L18','','L54',''),
('AB1','L60','L14','','L16','','L18','','','L56'),
('AC1','','','','','','','','','L56');
WITH UNPVT AS
(
SELECT *
FROM
(SELECT
A.CODE_NBR,
ListTable1 L1,
ListTable2 L2,
ListTable3 L3,
ListTable4 L4,
ListTable5 L5,
ListTable6 L6,
ListTable7 L7,
ListTable8 L8,
ListTable9 L9
FROM
PLANS A) TMP
UNPIVOT
(LISTS FOR
LISTALL IN (L1,L2,L3,L4,L5,L6,L7,L8,L9)
) UNPIV),
LISTCOUNT AS
(
SELECT
CODE_NBR, COUNT(LISTS) LCOUNT,
MIN(lists) firstlist, max(lists) lastlist
FROM
UNPVT
GROUP BY
CODE_NBR
),
PVT AS
(
SELECT *
FROM
(SELECT * FROM UNPVT) T1
PIVOT
(MAX(LISTS)
FOR LISTALL IN (L1,L2,L3,L4,L5,L6,L7,L8,L9)) T1
)
SELECT *
FROM PVT
5条答案
按热度按时间gtlvzcf81#
Sticking to your pivot approach:
After an
UNPIVOT
, UsingROW_NUMBER
you can reassign the column names and thenPIVOT
them back.hujrc8aj2#
Please try the following solution.
It is using XML and XQuery.
CROSS APPLY
is tokenizing each row as XML. Amazingly enough that XML is omitting columns with NULL values. By doing that we are shifting real data to the left.SQL
Output
raogr8fs3#
First put the values in a list, and then split them....
see: DBFIDDLE
P.S. The first try (in the dbfiddle) is a naive approach, which should be ignored... 😉
i86rm4rw4#
Here is the solution. I have made the solution dynamic. I tried to get the all the columns where you want to do the analysis and used pivot to find out your desired answer.
qnakjoqk5#
A manual unpivot-repivot without joins, xml/json, dynamic sql or special pivoting operators: