Postgresql 创建视图

问题描述 投票:0回答:2

我在表 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
sql postgresql view group-by aggregate-functions
2个回答
21
投票

这个应该可以完成这项工作:

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

0
投票

例如,您创建

person
表,如下所示。 我的帖子详细解释了一个观点:

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

然后,将 2 行插入到

person
表中,如下所示:

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

现在,您可以使用

my_view
语句创建
SELECT
视图,如下所示:

CREATE VIEW my_view AS
  SELECT first_name, last_name FROM person;

然后,您可以使用

my_view
语句的
FROM
子句来调用
SELECT
,如下所示:

postgres=# SELECT * FROM my_view;
 first_name | last_name
------------+-----------
 John       | Smith
 David      | Miller
(2 rows)
© www.soinside.com 2019 - 2024. All rights reserved.