I have the following columns in Table A which records users fingerprint "transaction" every time they check in or check out from a building.
CREATE TABLE user_transactions(
id serial PRIMARY KEY,
staff_id INT4,
transaction_time TIMESTAMP,
transaction_type INT4
);
In a single day a user can have many transactions. How can I create a view that with the following stucture?
staff_id INT4
transaction_date DATE
first_transaction TIMESTAMP --first finger scan of the day
last_transaction TIMESTAMP --last finger scan of the day
number_of_transaction INT4 --how many times did the user scan for the day
Creating Views The PostgreSQL views can be created from a single table, multiple tables, or another view.
To create a PostgreSQL view, we use the CREATE VIEW statement. Here is the syntax for this statement: CREATE [OR REPLACE] VIEW view-name AS SELECT column(s) FROM table(s) [WHERE condition(s)]; The OR REPLACE parameter will replace the view if it already exists.
Click the General tab to begin. Use the fields in the General tab to identify a view: Use the Name field to add a descriptive name for the view. The name of the view must be distinct from the name of any other view, table, sequence, index or foreign table in the same schema.
A Postgres view is a virtual table in Postgres. It represents the result of a query to one or more underlying tables in Postgres. Views are used to simplify complex queries since these queries are defined once in the view, and can then be directly queried via the same.
This one should do the job:
create or replace view xxx as
select
staff_id,
date_trunc('day', transaction_time) transaction_date,
min(transaction_time) first_transaction,
max(transaction_time) last_transaction,
count(*)
from user_transactions
group by staff_id, date_trunc('day', transaction_time);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With