Question

In: Computer Science

Create a report that lists customers with the total value of their orders from the database....

Create a report that lists customers with the total value of their orders from the database. Each row of the table should list the customer name and the total value of all orders. Rows should be in descending order according to the total. Just list the first 5 customers, those with the highest total orders.

This part is more complex and, so, can be approached in many ways. You may decide to use simple queries and put the information together using Python code. Alternatively, you might create a single SQL command that will produce the data needed.

Just one strategy will be outlined here, then some variants will be mentioned.

  • Start an empty list for all customers
  • Get a list of customers
    • For each customer get a list of invoices for that customer
      • initialize a variable to get the total of all invoices for the customer
      • For each invoice get a list of pizzas on that invoice
        • For each pizza, get a list of toppings on the pizza
          • Add up the costs of the toppings and add to the customer total
          • Add the crust price and sauce price to the customer total
      • Make a list of data about that customer and add to the list for all customers
  • Sort the list for all customers
  • Print the data

pizza_service.py

import sqlite3

class PizzaServices:

    def __init__(self):
        self.connection = sqlite3.connect("pizza-190807A.sqlite")

    def __enter__(self):
        return self

    def __exit__(self, exe_type, exc_val, exl_tb):
        crs = self.connection.cursor()

    def do_query(self, query, parameters=None):
        crs = self.connection.cursor()
        if parameters:
            crs.execute(query, parameters)
        else:
            crs.execute(query)

        return crs.fetchall()

    def customer(self):
        return self.do_query("select * from customer")

Solutions

Expert Solution

import sqlite3

class PizzaServices:

        def __init__(self):
                self.connection = sqlite3.connect("pizza-190807A.sqlite")

        def __enter__(self):
                return self

        def __exit__(self, exe_type, exc_val, exl_tb):
                crs = self.connection.cursor()

        def do_query(self, query, parameters=None):
                crs = self.connection.cursor()
                if parameters:
                        crs.execute(query, parameters)
                else:
                        crs.execute(query)
                return crs.fetchall()  # Do not indent it inside, it should execute in both if-else cases

        def customer(self):
                return self.do_query("select * from customer")

with PizzaServices() as cs:
        
        toppingPrices = {}
        for row in cs.do_query('select toppingId, price from topping'):                          
                toppingPrices[row[0]] = row[1]
        
        crustPrices = {}
        for row in cs.do_query('select crustId, price from crust'):                              
                crustPrices[row[0]] = row[1]
        
        saucePrices = {}
        for row in cs.do_query('select sauceId, price from sauce'):                              
                saucePrices[row[0]] = row[1]
        
        result = []
        for row in cs.do_query('select customerId, firstName, lastName from customer'):
        
                custId = row[0]
                invoices = cs.do_query('select invoiceId from invoice where customerId = (?)', (custId, ))
                totalAmount = 0
                
                for invoiceId in (list(map(lambda x: x[0], invoices))):
                        pizzas = cs.do_query('select pizzaId, crustId, sauceId, discount from pizza where invoiceId = (?)', (invoiceId, ))
                        
                        for pizza in pizzas:
                                pizzaId = pizza[0]
                                toppings = cs.do_query('select toppingId, pizzaId from pizzaTopping where pizzaId = (?)', (pizzaId, ))
                                
                                for topping in toppings:
                                        totalAmount += toppingPrices[topping[0]]
                                        
                                totalAmount += crustPrices[pizza[1]]
                                totalAmount += saucePrices[pizza[2]]
                                totalAmount -= pizza[3]
                        
                result.append((row[1], row[2], totalAmount))
        
        result = sorted(result, key=lambda x: x[2], reverse=True)
        print('{:<20} {:<20} {:<20}'.format('FirstName', 'LastName', 'OrderAmount'))
        for r in result:
                print('{:<20} {:<20} {:<20}'.format(r[0], r[1], r[2]))



                
                
                
                
                
                
                
**************************************************

Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.

Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.


Related Solutions

Create a report that lists all the customers in alphabetical order by last name. The report...
Create a report that lists all the customers in alphabetical order by last name. The report should include first name, last name, and email address of all customers. This report involves getting data from one table. The three items should be lined up in columns. Use one of the formatting functions available through Python (the % operator or the format function). Don’t use tabs to line up columns, this does not reliably work and is inflexible.1 Even though we won’t...
Create a report that lists each topping and also lists the number of pizzas that used...
Create a report that lists each topping and also lists the number of pizzas that used that topping. Order the report in decreasing order of number of pizzas. That is, the most popular toppings will be at the top of the report.2 In each row of the table list: the topping name; the price of the topping; the number of pizzas that used the topping; and, the total value of the topping (number of pizzas times topping price). Since some...
You are hired to create a database for a Real Estate firm that lists and sells...
You are hired to create a database for a Real Estate firm that lists and sells properties at multiple sales offices . Draw an ER diagram using ERDPlus for the following description of the firm, indicate all primary keys and cardinalities. List any assumptions you made. There are many sales offices in several states. Attributes of a sales office include office number (identifier) and location. Components of location include Address (number & street), City, State and Zip. Each sales office...
Create a Database from blank (scratch) for a manager and name it. Create and design a...
Create a Database from blank (scratch) for a manager and name it. Create and design a table and name it. For each fields click and choose proper a data type such as short text and name the field. Make at least three fields. Enter your records. Make sure to add your name as a record. Similarly create two more tables. By design tool, make a relationship between each of two tables at a time and drag a primary key one...
You are evaluating orders from two customers but can accept only one of the orders because...
You are evaluating orders from two customers but can accept only one of the orders because of your company's limited capacity. the first order is for 100 units of a product with a contribution margin ratio of 60% and a selling price of $1,000. The second order is for 500 units of a product with a contribution margin ratio of 20% and a selling price of $800. The incremental fixed costs are the same for both orders. Which order should...
Create an RDM that has entities, Customers, Products, Orders, Payments, and OrderDetails using MS ACCESS. For...
Create an RDM that has entities, Customers, Products, Orders, Payments, and OrderDetails using MS ACCESS. For each entity use the appropriate attributes and explain the relationship being used.
Create a web interface that has a backend database that takes a value of one table...
Create a web interface that has a backend database that takes a value of one table and displays it match from another table. Create a web interface, that has a backend database, the database contains two tables, one table contains courses in one curriculum, while the other table in the database has corresponding classes from another curriculum. A user should be able to pick a course from the curriculum, and the matching course from the other table should populate on...
Database exercise: inpatient cases Create database using name RUMKIT Create tables below in that database patient(idPatient,...
Database exercise: inpatient cases Create database using name RUMKIT Create tables below in that database patient(idPatient, fullName, biologicalMother, birthdate, address) doctor(idDr, fullName, specialization, consulRates) inpatient(idPatient, entryTime, outTime, idDr, idRoom). Please make entryTime as column that is going to be filled automatically when care record is being add room(idRoom, roomName, cost) fill the data above to each table Create sql query and relational algebra expressions for the query Please give me detailed answer so I could learn from it. Thank you...
At the end of the day, the cash register tape lists $881.40 as total income from...
At the end of the day, the cash register tape lists $881.40 as total income from services. Cash on hand consists of $18.25 in coins, $433.60 in currency, $100.00 in traveler's checks, and $427.00 in customers' checks. The amount of the Change Fund is $100. Required: Record the entry to record the day's cash revenue. If an amount box does not require an entry, leave it blank. GENERAL JOURNAL PAGE       DATE DESCRIPTION DOC. NO. POST. REF. DEBIT CREDIT To record...
Case Customers make purchases from AMT by emailing their purchase orders. On receipt of a customer’s...
Case Customers make purchases from AMT by emailing their purchase orders. On receipt of a customer’s purchase order, a Sales Clerk prepares a Sales Order. In doing so, he accesses an authorised price list to determine the price that is to be charged, and inputs the quantities, product descriptions, product codes and delivery requirements. Sales Orders are prenumbered and in triplicate. The Sales Clerk then performs a credit check by comparing the value of the sale with the customer’s credit...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT