Search code examples
postgresqlinsertnestedcreate-tablenested-table

Import Data to a new table that has a nested table in it


INSERT INTO OrderNew (
SalesOrderID,
OrderDate,
DueDate,
ShipDate,
OnlineOrderFlag,
CustomerID,
CreditCardID,
SubTotal,
TaxAmt,
Freight,
TotalDue,
OrderInfo.salesorderdetail,
OrderInfo.orderqty ,
OrderInfo.productid, 
OrderInfo.unitprice,
OrderInfo.unitpricediscount,
OrderInfo.linetotal
)
SELECT h."SalesOrderID" , h."OrderDate", h."DueDate", h."ShipDate", h."OnlineOrderFlag", h."CustomerID", h."CreditCardID", h."SubTotal", h."TaxAmt", h."Freight", h."TotalDue", d."SalesOrderDetailID", d."OrderQty", d."ProductID", d."UnitPrice", d."UnitPriceDiscount", d."LineTotal"
FROM "SalesOrderHeader" h
INNER JOIN "SalesOrderDetail" d ON  d."SalesOrderID" = h."SalesOrderID"
WHERE d."SalesOrderID" = h."SalesOrderID" ;

This is the code I use in order to import data from some other tables. However, I want the last column to be like a nested table. These are the tables that I want to be one. So for one Sales Order ID from the table "SalesOrderHeader" there are a couple or more records with the same Sales Order ID on the table "SalesOrderDetail". So, how can I do it? Using a function?

I don't know if I am an understandable. But I can give more information.


Solution

  • You create two types in order to shrink a bit the new table which is going to be a combination of the SalesOrderHeader and SalesOrderDetail.

    CREATE TYPE Shipping AS(OrderDate Date,DueDate Date,ShipDate Date);

    CREATE TYPE ordersdetails AS (details text);

    Then you create the table.

    CREATE TABLE ordernew ( salesorderid serial NOT NULL, shippinginfo shipping, onlineorderflag integer, customerid serial NOT NULL, creditcardid integer, subtotal real, taxamt real, freight real, totaldue real, orderinfo ordersdetails[]);
    

    As for the data, you will just copy the data from the other two tables but writing a right query in order not to create duplicate records. So, the code is below.

    INSERT INTO OrderNew (
    SalesOrderID,
    OrderDate,
    DueDate,
    ShipDate,
    OnlineOrderFlag,
    CustomerID,CreditCardID,
    SubTotal,
    TaxAmt,
    Freight,
    TotalDue,
    OrderInfo.salesorderdetail,
    OrderInfo.orderqty ,
    OrderInfo.productid,
    OrderInfo.unitprice,
    OrderInfo.unitpricediscount,
    OrderInfo.linetotal
    )
    SELECT h."SalesOrderID" , h."OrderDate", h."DueDate", h."ShipDate", h."OnlineOrderFlag",
    h."CustomerID", h."CreditCardID", h."SubTotal", h."TaxAmt", h."Freight", h."TotalDue",
    d."SalesOrderDetailID", d."OrderQty", d."ProductID", d."UnitPrice", d."UnitPriceDiscount", d."LineTotal"
    FROM "SalesOrderHeader" h
    INNER JOIN "SalesOrderDetail" d ON d."SalesOrderID" = h."SalesOrderID"
    WHERE d."SalesOrderID" = h."SalesOrderID" ;
    

    To simply view the data that you recently inserted just run the following query:

    SELECT orderinfo FROM ordernew;