Postgresql 创建视图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8578385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-20 23:29:20  来源:igfitidea点击:

Postgresql create view

sqlpostgresqlviewsgroup-byaggregate-functions

提问by Random Joe

I have the following columns in Table A which records users fingerprint "transaction" every time they check in or check out from a building.

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

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

回答by A.H.

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