Pergunta

My query currently produces output with the Part Number as one value:

SELECT UPPER(PartNumber)AS "Part Number",
    INITCAP(PartDesc)AS "Description"
FROM Part 
WHERE UnitPrice*UnitsOnHand <1000
ORDER BY PartDesc DESC;

Part Number Description                            
----------- ----------------------------------------
BA74        Baseball Bat                             
CA14        Skillet - 12 Inch                        
AZ52        Roller Skates                            

The result should still be 2 columns, but modified:

Part Number Description                            
----------- ----------------------------------------
BA-74       Baseball Bat                             
CA-14       Skillet - 12 Inch                        
AZ-52       Roller Skates                            

Part Number will always have alpha/numeric characters, Description is just alpha. What I need to be able to do is insert a hyphen between the alpha and numerical characters. They will always be alpha/numeric never change.

Foi útil?

Solução

The question is still missing some details, but if I've got your pattern right, and you want to separate the first block of just alphabetic characters from everything else with a hyphen, you can use a pair of regular expressions and string concatenation:

SELECT UPPER(
      REGEXP_SUBSTR(PartNumber, '[[:alpha:]]+')
      ||'-'||
      REGEXP_SUBSTR(PartNumber, '[^[:alpha:]]+.*')
    ) AS "Part Number",
    INITCAP(PartDesc)AS "Description"
FROM Part 
WHERE UnitPrice*UnitsOnHand <1000
ORDER BY PartDesc DESC;

Part Number           Description                  
--------------------- ------------------------------
CA-14                 Skillet - 12 Inch              
AZ-52                 Roller Skates                  
BA-74                 Baseball Bat                   

This will work for more complicated values, as long as the part number always starts with a character:

WITH Part AS (
    SELECT 'b9a74' AS PartNumber, 'baseball BAT' AS PartDesc,
        20 AS UnitPrice, 20 AS UnitsOnHand FROM DUAL
    UNION ALL SELECT 'ca14a1', 'sKiLlEt - 12 iNCH', 20, 20 FROM DUAL
    UNION ALL SELECT 'aza52', 'roller sKaTeS', 20, 20 FROM DUAL
)
SELECT UPPER(
      REGEXP_SUBSTR(PartNumber, '[[:alpha:]]+')
      ||'-'||
      REGEXP_SUBSTR(PartNumber, '[^[:alpha:]]+.*')
    ) AS "Part Number",
    INITCAP(PartDesc)AS "Description"
FROM Part 
WHERE UnitPrice*UnitsOnHand <1000
ORDER BY PartDesc DESC;

Part Number   Description     
------------- -----------------
CA-14A1       Skillet - 12 Inch 
AZA-52        Roller Skates     
B-9A74        Baseball Bat      

But note that it always inserts a single hyphen, which seems to be what you want; it doesn't separate all groups of characters and numbers (e.g. B9A74 to B-9-A-74). It just puts a hyphen before the first non-alpha character.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top