SQL Exercises: View to show the number of orders in each day

SQL VIEW: Exercise-14 with Solution

14. From the following table, create a view to display the number of orders per day. Return order date and number of orders.

Sample table: orders

Sample Solution:

-- Creating a VIEW named 'dateord' with columns 'ord_date' and 'odcount'
CREATE VIEW dateord(ord_date, odcount)

-- Selecting distinct order dates and counting the number of orders for each date
-- Using the 'orders' table and grouping by 'ord_date'
AS SELECT ord_date, COUNT (*)
FROM orders 
GROUP BY ord_date;


sqlpractice=# SELECT *
sqlpractice-# FROM dateord;
  ord_date  | odcount
 2012-10-05 |       2
 2012-08-17 |       3
 2012-07-27 |       1
 2012-09-22 |       1
 2012-09-10 |       3
 2012-10-10 |       2
 2012-06-27 |       1
 2012-04-25 |       1
(8 rows)

Code Explanation:

The provided statement in SQL creates a view named dateord, which returns the count of orders placed on each unique order date.
The COUNT function have used to return the total number of orders on each unique order date.
Then groups the results by the ord_date column and returns the count of orders for each unique order date.

Inventory database model:

Inventory database model

Contribute your code and comments through Disqus.

Previous SQL Exercise: View to show all matches of customers with salesmen.
Next SQL Exercise: View to show the salesmen issued orders on given date.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.