Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql create view

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
like image 640
Random Joe Avatar asked Dec 20 '11 16:12

Random Joe


People also ask

Can we create views in PostgreSQL?

Creating Views The PostgreSQL views can be created from a single table, multiple tables, or another view.

How do I create a new PostgreSQL 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.

How do you create a view in pgAdmin 4?

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.

What is a Postgres view?

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.


1 Answers

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);
like image 146
A.H. Avatar answered Oct 06 '22 01:10

A.H.