在PostgreSQL中创建视图

kiz8lqtg  于 2024-01-07  发布在  PostgreSQL
关注(0)|答案(2)|浏览(194)

我在表A中有以下几列记录用户每次登记入住或退房时的指纹“交易”。

CREATE TABLE user_transactions (
  id serial PRIMARY KEY,
  staff_id INT4,
  transaction_time TIMESTAMP,
  transaction_type INT4
);

字符串
一个用户在一天之内可以有很多事务。我如何创建一个具有以下结构的视图?

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

to94eoyn

to94eoyn1#

这一个应该做的工作:

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);

字符串

s1ag04yj

s1ag04yj2#

例如,您创建person表,如下所示。My post详细解释了一个视图:

CREATE TABLE person (
  id INTEGER,
  first_name VARCHAR(20),
  last_name VARCHAR(20),
  age INTEGER
);

字符串
然后,将两行插入person表,如下所示:

INSERT INTO person (id, first_name, last_name, age) 
VALUES (1, 'John', 'Smith', 27), (2, 'David', 'Miller', 32);


现在,您可以使用SELECT语句创建my_view视图,如下所示:

CREATE VIEW my_view AS
  SELECT first_name, last_name FROM person;


然后,您可以使用SELECT语句的FROM子句调用my_view,如下所示:

postgres=# SELECT * FROM my_view;
 first_name | last_name
------------+-----------
 John       | Smith
 David      | Miller
(2 rows)

相关问题