sqldual-table

How can DUAL be used for something other than calculating an equation?


I am trying to understand how DUAL, which from my understanding, is used to calculate an equation (SELECT (4+3) FROM DUAL;), can be used create a table as well. Given these two tables, "Items" and "Items_Related":

Items:

Item_Number
24-1
24-2
24-3
24-4
24-5

Items_Related:

Master_Item Related_Item
24-1 24-2
24-1 24-3
24-1 24-4
24-1 24-5
24-2 24-1
24-3 24-1
24-4 24-1
24-5 24-1

How can the following query:

SELECT ITEMS.ITEM_NUMBER, (SELECT DATABASE.ROWS_TO_HTML (SELECT RELATED_ITEM || FROM ITEMS_RELATED || WHERE ITEMS_RELATED.MASTER_ITEM = ``` || ITEMS.ITEM_NUMBER || ```` || `` || ORDER BY ITEMS_RELATED.RELATED_ITEM`) FROM DUAL) AS RELATED_ITEM FROM ITEMS ;

create this table, where 24-1 in the ITEM_NUMBER field is one merged cell when the table is exported as an Excel spreadsheet, and the rest are all separate:

ITEM_NUMBER RELATED_ITEM
24-1 24-2
24-3
24-4
24-5
24-2 24-1
24-3 24-1
24-4 24-1
24-5 24-1

When I tried to input a test query into oracle SQL developer, such as:

SELECT ('SELECT ITEM_NUMBER' || 'FROM ITEMS') FROM DUAL;

the result was:

'SELECT ITEM_NUMBER.....

SELECT ITEM_NUMBERFROM ITEMS


Solution

  • I am not sure if you really need DUAL, I think you can utilise the two tables ITEMS and ITEMS_RELATED and get the required output, let us know.

    Fiddle

    SELECT 
        CASE 
            WHEN ROW_NUMBER() OVER (PARTITION BY ir.MASTER_ITEM ORDER BY ir.RELATED_ITEM) = 1
            THEN ir.MASTER_ITEM
            ELSE NULL
        END AS ITEM_NUMBER,
        ir.RELATED_ITEM
    FROM 
        ITEMS_RELATED ir
    JOIN 
        ITEMS i
        ON ir.MASTER_ITEM = i.ITEM_NUMBER
    ORDER BY 
        ir.MASTER_ITEM, ir.RELATED_ITEM;
    

    Output

    enter image description here