查询以输出每种类型的最大电影票

时间:2019-03-14 01:45:50

标签: sql postgresql

我试图找出在每种类型中观看最多电影数量的客户。该查询将输出记录中所有客户中观看最多的customerId和movieGenre。如果没有任何人观看movieGenre,则将在输出中将其忽略。如果将客户捆绑到moviegenre,则将输出所有捆绑的客户。

以下是架构:

CREATE TABLE customers ( 
    customerId      INTEGER PRIMARY KEY,
    customerName    VARCHAR(20),
    city            CHAR(20)     
);

CREATE TABLE movies (  
    movieId         INTEGER PRIMARY KEY,
    movieGenre      VARCHAR(20),
    moviePrice      NUMERIC(10,2)
);

CREATE TABLE tickets (    
    ticketId      INTEGER PRIMARY KEY,
    ticketDate    DATE,        
    customerId    INTEGER NOT NULL REFERENCES customers
);

CREATE TABLE details (    
    ticketId            INTEGER REFERENCES tickets,  
    movieId             INTEGER REFERENCES movies, 
    numOfTickets        SMALLINT,
    PRIMARY KEY (ticketId, movieId)
);

CREATE TABLE transactions (   
    transactionId       SERIAL PRIMARY KEY,
    ticketId            INTEGER NOT NULL UNIQUE REFERENCES tickets,
    transactionAmount   NUMERIC(8,2)    
);

CREATE TABLE Payments (   
    paymentId       INTEGER PRIMARY KEY,
    paymentAmount   NUMERIC(8,2) CHECK ( amount > 0 ),
    transactionId   INTEGER NOT NULL REFERENCES transactions
);

这是我的查询

select m.movieGenre, max(c.customerId) 
from movies m join details d 
    on m.movieId = d.movieId join tickets t 
    on d.ticketId = t.ticketId join customers c 
    on t.customerId < c.customerId 
group by m.movieGenre;

我的查询针对所有电影类型输出96,这是不正确的。谁能帮我解决这个问题?

1 个答案:

答案 0 :(得分:1)

您需要获取数据中所有对的客户/类型计数。我认为是这样:

select m.movieGenre, t.customerId, count(*)
from movies m join
     details d 
     on m.movieId = d.movieId join
     tickets t 
     on d.ticketId = t.ticketId 
group by m.movieGenre, t.customerId;

然后要获取每个组的最大值,请使用distinct on

select distinct on (m.movieGenre) m.movieGenre, t.customerId, count(*)
from movies m join
     details d 
     on m.movieId = d.movieId join
     tickets t 
     on d.ticketId = t.ticketId 
group by m.movieGenre, t.customerId
order by m.movieGenre, count(*) desc;