Skip to content
Advertisement

Combine like rows based on substring of one column?

I have a table of parts that looks like this:

Part Part Num Thing1 Thing2 Thing3 Thing4
Door 10105322 abc abc
Door 10105323 abc abc
Door 10105324 abc abc
Door 84625111 abc abc abc
Door 84625118 abc abc abc
Door 84625185 abc abc abc
Door 56897101 abc abc

The part number is always 8 characters. For many parts, the first 6 characters are the same, and the last 2 are different. Lines where the first 6 characters of a part number are the same and all rows that have the same values in Thing1/Thing2/Thing3/Thing4 need to be combined, and the part number becomes 6 characters. (row 1/2/3 in the above table)

Lines where the first 6 characters are the same but the values in Thing1/Thing2/Thing3/Thing4 are NOT identical in all rows need to remain unchanged and the part number remains 8 characters. (row 4/5/6 in the above table)

Lines where the first 6 characters are unique need to remain unchanged and the part number remains 8 characters. (row 7 in the above table)

The desired result would look like:

Part Part Num Thing1 Thing2 Thing3 Thing4
Door 101053 abc abc
Door 84625111 abc abc abc
Door 84625118 abc abc abc
Door 84625185 abc abc abc
Door 56897101 abc abc

Advertisement

Answer

Use COUNT() window function:

WITH cte AS (
  SELECT *,
         COUNT(*) OVER (PARTITION BY Part, LEFT(PartNum, 6), Thing1, Thing2, Thing3, Thing4) counter1,
         COUNT(*) OVER (PARTITION BY Part, LEFT(PartNum, 6)) counter2
  FROM tablename
)
SELECT DISTINCT
  Part,
  CASE WHEN counter1 > 1 AND counter1 = counter2 THEN LEFT(PartNum, 6) ELSE PartNum END PartNum,
  Thing1, Thing2, Thing3, Thing4 
FROM cte;

See the demo.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement