简体   繁体   中英

Creating a customer-order monthly report

The report must include the following information: customer's name, complete address, old balance, new balance and number of items that have been ordered by that customer during that period(31-Mar-2019).assuming that current balances shown are correct as of the end of February 2019.

This is what I have tried so far, it just displays the orders on that month but I having trouble including the old balance and new balance of question. I feel it is still far off from what is required.

select c.name, c.address, c.balance, i.qty 
from customer c, "order" o, order_item i  
where o."date" <='31-Mar-2019';

These are the tables I am working with

oracle sql

create table customer (  
    name varchar(100) primary key, 
    address varchar(200), 
    balance integer); 

create table "order" ( 
    order_no number primary key, 
    "date" date, 
    cust varchar(100),
    foreign key(cust) references customer(name)); 

create table order_item ( 
    order_no number, 
    item_name varchar(100), 
    qty number,
    primary key (order_no,item_name),
    foreign key(order_no) references "order"(order_no)
);   

Each customer must be included only once in the result (ie as one row), and the results must be in ascending order of account number.

Your data model has serious issues.

A balance is normally an amount of money. However, although your order_item table has a qty there is no associated cost. Consequently it is impossible to calculate the new balance from the data provided structures. It seems you have a missing table - item ? - which has this crucial piece of information.

Also, it is nonsense to have the concept of a "current" balance without any notion of when that balance was last calculated. We're just supposed to know it was "correct as of the end of February 2019" .

Also, using things like customer.name as a primary key is poor. Primary keys should be immutable and people often change their names.

Finally, using Oracle key words like "order" and "date" for names is unspeakable. Don't force people to enclose the object names in double-quotes. Just don't. Choose sensible names instead.

Anyway, let's get to work:

select c.name
       , c.address
       , c.balance as current_balance
       , sum(oi.qty) as total_items_ordered
       , c.balance + (oi.qty * i.price) as new_balance
from customer c
     join "order" o on o.cust = c.name
     join order_item oi on oi.order_no = o.order_no
     join supplier i on i.name = oi.item_name 
 where o."date" <='31-Mar-2019'
 group by c.name
       , c.address
       , c.balance;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM