SQL Server电影院数据库管理系统【英文版-源码】--(Movie Theatre Management System Database)

友情连接

1、医疗信息管理系统数据库–MySQL

医疗信息管理系统数据库–MySQL

2、邮件管理数据库设计–MySQL

邮件管理数据库设计–MySQL

3、学生成绩管理系统数据库设计–MySQL

学生成绩管理系统数据库设计–MySQL

4、点餐系统数据库设计–SQL Server

点餐系统数据库设计–SQL Server

5、商品管理系统数据库设计–SQL Server

商品管理系统数据库设计–SQL Server

6、SQL Server医疗信息管理系统数据库【英文版-源码】–(Medical Management System Database)

SQL Server医疗信息管理系统数据库【英文版-源码】–(Medical Management System Database)

1. 创建数据库及数据表、插入数据


--******Create/Drop Databse******

-- if MovieTheatre exists, kill current connections to Database
-- make single user
IF DB_ID('MovieTheatre') IS NOT NULL
	BEGIN
		USE [MASTER];

		ALTER	DATABASE [MovieTheatre] 
		SET 	SINGLE_USER
		WITH	ROLLBACK IMMEDIATE;

		DROP DATABASE MovieTheatre;
	END
GO

-- create new database called MovieTheatre
CREATE DATABASE MovieTheatre;
GO

USE MovieTheatre;
GO

--******Create Tables*******

--Classifications
DROP TABLE IF EXISTS Classifications
GO
CREATE TABLE Classifications
(
	classification CHAR(2) NOT NULL PRIMARY KEY,
	classificationName VARCHAR(150) NOT NULL,
	classificationMinimumAge CHAR(14) NOT NULL,
);
GO


--Movies Tbl
DROP TABLE IF EXISTS Movies
GO
CREATE TABLE Movies
(
	movieId INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
	movieName VARCHAR(150) NOT NULL,
	movieDuration SMALLINT NOT NULL,
	movieDescription VARCHAR(MAX) NOT NULL,
	classification CHAR(2) NOT NULL FOREIGN KEY REFERENCES Classifications(classification),
);
GO


-- Genres 
DROP TABLE IF EXISTS Genres
GO
CREATE TABLE Genres
(
	genresId INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
	genresType VARCHAR(40) NOT NULL
);
GO


-- MoviesGenres
DROP TABLE IF EXISTS MoviesGenres
GO
CREATE TABLE MoviesGenres
(
	movieId INT NOT NULL	FOREIGN KEY  REFERENCES Movies(movieId),
	genresId INT NOT NULL	FOREIGN KEY  REFERENCES Genres(genresId),
	PRIMARY KEY (movieId, genresId),
);
GO


-- CinemasTypes 
DROP TABLE IF EXISTS CinemasTypes
GO
CREATE TABLE CinemasTypes
(
	cinemaTypeId INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
	cinemaTypeName VARCHAR(40) NOT NULL
);
GO


-- Cinemas 
DROP TABLE IF EXISTS Cinemas
GO
CREATE TABLE Cinemas
(
	cinemaId INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
	cinemaName VARCHAR(40) NOT NULL,
	cinemaSeatingCapacity INT NOT NULL DEFAULT 0,
	cinemaTypeId INT NOT NULL   FOREIGN KEY  REFERENCES CinemasTypes(cinemaTypeId),
);
GO


-- Sessions
DROP TABLE IF EXISTS MovieSessions
GO
CREATE TABLE MovieSessions
(
	sessionId INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
	sessionDateTime DATETIME NOT NULL,
	sessionTicketCost MONEY NOT NULL DEFAULT 0,
	cinemaId INT NOT NULL FOREIGN KEY  REFERENCES Cinemas(cinemaId),
	movieId INT NOT NULL  FOREIGN KEY  REFERENCES Movies(movieId),
);
GO


-- Customers
DROP TABLE IF EXISTS Customers
GO
CREATE TABLE Customers
(
	customerEmail VARCHAR(100) NOT NULL PRIMARY KEY,
	customerPassword VARCHAR(70) NOT NULL,
	customerFirstName VARCHAR(70) NOT NULL,
	customerLastName VARCHAR(70) NOT NULL,
	customerDOB DATE NOT NULL,
);
GO


-- TicketPurchases
DROP TABLE IF EXISTS TicketPurchases
GO
CREATE TABLE TicketPurchases
(
	ticketPurchaseId INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
	ticketPurchaseNumberPurchased INT NOT NULL,
	customerEmail VARCHAR(100) NOT NULL FOREIGN KEY  REFERENCES Customers(customerEmail),
	sessionId INT NOT NULL FOREIGN KEY  REFERENCES MovieSessions(sessionId),
);
GO


-- CustomersReviews
DROP TABLE IF EXISTS CustomersReviews
GO
CREATE TABLE CustomersReviews -- customer Can only review a movie ONCE
(
	customersReviewId INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
	customersReviewText VARCHAR(MAX) NOT NULL,
	customersReviewRating SMALLINT NOT NULL CHECK (customersReviewRating > -1 AND customersReviewRating < 6),
	customersReviewDateTime DATETIME DEFAULT Getdate(),
	customerEmail VARCHAR(100) NOT NULL FOREIGN KEY  REFERENCES Customers(customerEmail),
	movieId INT NOT NULL FOREIGN KEY  REFERENCES Movies(movieId),
);
GO


--******Database Population*******

INSERT INTO Classifications
VALUES ('G',  'General', 'Not Applicable'),
       ('PG', 'Parental Guidance', 'Not Applicable'),
       ('M',  'Mature', 'Not Applicable'),
       ('MA', 'Mature Audiences', '15'),
       ('R',  'Restricted', '18');


INSERT INTO Genres (genresType)
VALUES ('Action'),     -- Genre 1
       ('Adventure'),  -- Genre 2
       ('Animation'),  -- Genre 3
       ('Comedy'),     -- Genre 4
       ('Crime'),      -- Genre 5
       ('Drama'),      -- Genre 6
       ('Fantasy'),    -- Genre 7
       ('Horror'),     -- Genre 8
       ('Romance'),    -- Genre 9
       ('Sci-Fi');     -- Genre 10


INSERT INTO Movies
VALUES ('The Shawshank Redemption', 142, 'Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.', 'MA'),
       ('Pulp Fiction', 154, 'The lives of two mob hit men, a boxer, a gangster''s wife, and a pair of diner bandits intertwine in four tales of violence and redemption.', 'R'),
       ('Forrest Gump', 142, 'Forrest Gump, while not intelligent, has accidentally been present at many historic moments, but his true love, Jenny Curran, eludes him.', 'M'),
       ('Star Wars: Episode IV - A New Hope', 121, 'Luke Skywalker joins forces with a Jedi Knight, a cocky pilot, a wookiee and two droids to save the universe from the Empire''s world-destroying battle-station.', 'PG'),
       ('WALL-E', 98, 'In the distant future, a small waste collecting robot inadvertently embarks on a space journey that will ultimately decide the fate of mankind.', 'G'),
       ('Eternal Sunshine of the Spotless Mind', 108, 'When their relationship turns sour, a couple undergoes a procedure to have each other erased from their memories. But it is only through the process of loss that they discover what they had to begin with.', 'M'),
       ('Monty Python and the Holy Grail', 91, 'King Arthur and his knights embark on a low-budget search for the Grail, encountering many very silly obstacles.', 'PG'),
       ('Up', 96, 'Seventy-eight year old Carl Fredricksen travels to Paradise Falls in his home equipped with balloons, inadvertently taking a young stowaway.', 'PG'),
       ('Gran Torino', 116, 'Disgruntled Korean War veteran Walt Kowalski sets out to reform his neighbor, a Hmong teenager who tried to steal Kowalski''s prized possession: a 1972 Gran Torino.', 'M'),
       ('Metropolis', 153, 'In a futuristic city sharply divided between the working class and the city planners, the son of the city''s mastermind falls in love with a working class prophet who predicts the coming of a savior to mediate their differences.', 'PG');


INSERT INTO MoviesGenres
VALUES (1, 5), (1, 6),           -- Shawshank: Crime & Drama
       (2, 5), (2, 6),           -- Pulp Fiction: Crime & Drama
       (3, 6), (3, 9),           -- Forrest Gump: Drama & Romance
       (4, 1), (4, 2), (4, 7),   -- Star Wars: Action & Adventure & Fantasy
       (5, 2), (5, 3),           -- Wall-E: Adventure & Animation
       (6, 6), (6, 9), (6, 10),  -- Eternal Sunshine: Drama & Romance & Sci-Fi
       (7, 2), (7, 4), (7, 7),   -- Holy Grail: Adventure & Comedy & Fantasy
       (8, 2), (8, 3),           -- Up: Adventure & Animation
       (9, 6),                   -- Gran Torino: Drama
       (10, 6), (10, 10);        -- Metropolis: Drama & Sci-Fi

INSERT INTO CinemasTypes
VALUES	('2D'),
		('3D'),
		('Gold Class 2D'),
		('Gold Class 3D');	   


INSERT INTO Cinemas
VALUES	('Cinema 1',250,1),		--2D
		('Cinema 2',80,2),		--3D
		('Cinema 3',65,1),		--2D
		('Cinema 4',25,4),		--Gold Class 3D
		('Cinema 5',90,3),		--Gold Class 2D
		('Cinema 6',30,2),		--3D
		('Cinema 7',80,1);		--2D


INSERT INTO Customers
VALUES	('[email protected]','123test','Fred','Nurk',convert(datetime,'20/10/2000', 103)),
		('[email protected]','deathstar','Darth','Vader',convert(datetime,'2/10/1892',103)),
		('[email protected]','testp@wagain','Joe','Bloggs',convert(datetime,'24/5/1974', 103)),
		('[email protected]','afst%32k+','Sally','Hatsumitsu',convert(datetime,'13/9/2002', 103)),
		('[email protected]','resfjgt&dhfk++','Santa','Cruz',convert(datetime,'31/1/1983', 103)),
		('[email protected]','password','Joanne','Lumney',convert(datetime,'3/10/1948', 103)),
		('[email protected]','gdgdgdg3549%^','Hettie','Blowfeld',convert(datetime,'14/2/1990', 103));


INSERT INTO CustomersReviews 
		(customersReviewText, 
		 customersReviewRating,
		 customerEmail,
		 movieId) 
VALUES	('This movie was soo good! I loved the very bad ending. Please have more like this',4,'[email protected]',5),
		('Worst depiction of me EVER!',0,'[email protected]',4),
		('Pulp is a good word to describe this film. So much in need of a good tree mulching machine to turn it into pulp.',1,'[email protected]',2),
		('Loved this film. I can watch it over and over',5,'[email protected]',4),
		('I felt a real wally watching this film, but I enjoyed it enough to not walk out before the end.',3,'[email protected]',5),
		('I nearly fell asleep in the first five minutes. I will only see again if I am too tired from completing Uni assignments. Sorry Forest - you bored me to sleep.',2,'[email protected]',3);

INSERT INTO MovieSessions
VALUES	(convert(datetime,'1/12/2019 10:00:000', 103),12.50,1,1),
		(convert(datetime,'1/12/2019 22:00:000', 103),16.50,2,2),
		(convert(datetime,'1/12/2019 20:30:000', 103),12.50,3,4),
		(convert(datetime,'1/12/2019 22:00:000', 103),32.50,4,6),
		(convert(datetime,'23/1/2020 22:00:000', 103),24.00,5,1),
		(convert(datetime,'4/11/2019 22:00:000', 103),16.50,6,10),
		(convert(datetime,'1/12/2019 22:00:000', 103),12.50,7,7),
		(convert(datetime,'12/12/2019 22:00:000', 103),16.50,1,5),
		(convert(datetime,'12/12/2019 22:00:000', 103),16.50,2,6),
		(convert(datetime,'12/12/2019 22:00:000', 103),16.50,3,2),
		(convert(datetime,'12/12/2019 22:00:000', 103),32.50,4,9),
		(convert(datetime,'12/12/2019 22:00:000', 103),24.00,5,8),
		(convert(datetime,'13/12/2019 22:00:000', 103),16.50,6,3),
		(convert(datetime,'13/12/2019 22:00:000', 103),12.50,7,4);


INSERT INTO TicketPurchases
VALUES	(2,'[email protected]',3),
		(1,'[email protected]',2),
		(10,'[email protected]',3),
		(1,'[email protected]',9),
		(3,'[email protected]',6),
		(1,'[email protected]',14),
		(2,'[email protected]',8);

2. 查询数据


USE MovieTheatre;

-- Query 1 � Child Friendly Movies
-- SELECT movie name, duration and classification of all movies 
-- WHERE:
--    duration of less than 100 minutes 
--    a classification of �G� or �PG�.  
-- Order the results by duration. 

SELECT		movieName, 
			movieDuration, 
			classification
FROM		dbo.Movies
WHERE		(movieDuration < 100) AND 
			(classification IN ('G', 'PG'))
ORDER BY	movieDuration;



-- Query 2 � Movie Search 
-- SELECT the movie name, session date/time, cinema type name and cost of all upcoming sessions (i.e. session date/time is later than the current date/time) 
-- WHERE: 
--    �star wars� anywhere in the movie name  
-- Order the results by session date/time

SELECT		dbo.Movies.movieName, 
			dbo.vSession.sessionDateTime, 
			dbo.vSession.sessionTicketCost,
			dbo.vSession.cinemaTypeName
FROM		dbo.vSession INNER JOIN
				dbo.Movies ON dbo.vSession.movieId = dbo.Movies.movieId
WHERE		(dbo.Movies.movieName LIKE '%star wars%') AND (dbo.vSession.sessionDateTime > GETDATE())
ORDER BY	dbo.vSession.sessionDateTime;



-- Query 3 � Review Details
-- SELECT text of the reviewdetails,date/time the review was posted, the rating given, the first name,  age (calculated from the date of birth)
-- WHERE:
--    movie ID number of 5
-- Order the results by the review date, in descending order

SELECT		dbo.CustomersReviews.customersReviewText, 
			dbo.CustomersReviews.customersReviewDateTime, 
			dbo.CustomersReviews.customersReviewRating, 
			dbo.Customers.customerFirstName, 
			FLOOR(DATEDIFF(DAY, dbo.Customers.customerDOB, GETDATE()) / 365.25) AS Age
FROM		dbo.CustomersReviews INNER JOIN
				dbo.Customers ON dbo.CustomersReviews.customerEmail = dbo.Customers.customerEmail
WHERE		(dbo.CustomersReviews.movieId = 5)
ORDER BY	dbo.CustomersReviews.customersReviewDateTime DESC;



-- Query 4 � Genre Count
-- SELECT the name of all genres in the genre table, and the number of movies of each genre
--    show all genres, even if there are no movies of that genre in the database

SELECT		dbo.Genres.genresType AS Genres, 
			COUNT(dbo.MoviesGenres.movieId) AS MovieCount
FROM		dbo.Genres LEFT OUTER JOIN
				dbo.MoviesGenres ON dbo.Genres.genresId = dbo.MoviesGenres.genresId
GROUP BY	dbo.Genres.genresType;



-- Query 5 � Movie Review Stats
-- SELECT names of all movies in the movie table, how many reviews have been posted per movie, and the average star rating of the reviews per movie
--    include all movies, even if they have not been reviewed
--    Round the average rating to one decimal place
--  order the results by the average rating, in descending order

SELECT		dbo.Movies.movieName, 
			COUNT(dbo.CustomersReviews.movieId) AS MovieReviewCount, 
			AVG(CAST(dbo.CustomersReviews.customersReviewRating AS FLOAT(1))) AS AverageStarRating
FROM		dbo.Movies LEFT OUTER JOIN
				dbo.CustomersReviews ON dbo.Movies.movieId = dbo.CustomersReviews.movieId
GROUP BY	dbo.Movies.movieName
ORDER BY	AVG(CAST(dbo.CustomersReviews.customersReviewRating AS FLOAT(1))) DESC;



-- Query 6 � Top Selling Movies
-- SELECT name and total number of tickets sold of the THREE most popular movies (determined by total ticket sales)

SELECT		TOP (3) dbo.vSession.movieName, 
			SUM(dbo.TicketPurchases.ticketPurchaseNumberPurchased) AS TotalTicketsSold
FROM		dbo.vSession INNER JOIN
				dbo.TicketPurchases ON dbo.vSession.sessionId = dbo.TicketPurchases.sessionId
GROUP BY	dbo.vSession.movieName
ORDER BY	TotalTicketsSold DESC;



-- Query 7 � Customer Ticket Stats
-- SELECT full names (by concatenating their first name and last name) of all customers in the customer table, how many tickets they have each purchased, and the total cost of these tickets
--    include all customers, even if they have never purchased a ticket
-- Order the results by total ticket cost, in descending order

SELECT		dbo.Customers.customerFirstName + ' ' + dbo.Customers.customerLastName AS CustomerName, 
			ISNULL(SUM(dbo.TicketPurchases.ticketPurchaseNumberPurchased),0) AS TicketsPurchased, 
            ISNULL(SUM(dbo.TicketPurchases.ticketPurchaseNumberPurchased * dbo.MovieSessions.sessionTicketCost),0) AS TotalSpent
FROM		dbo.MovieSessions RIGHT OUTER JOIN
				dbo.TicketPurchases ON dbo.MovieSessions.sessionId = dbo.TicketPurchases.sessionId RIGHT OUTER JOIN
				dbo.Customers ON dbo.TicketPurchases.customerEmail = dbo.Customers.customerEmail
GROUP BY	dbo.Customers.customerFirstName + ' ' + dbo.Customers.customerLastName
ORDER BY	TotalSpent DESC;



-- Query 8 � Age Appropriate Movies
-- SELECT movie name, duration and description of all movies that a certain customer (chosen by you) can legally watch, 
-- WHERE:
--	 based on the customer�s date of birth and the minimum age required by the movie�s classification
-- SUB QUERY:
--	 SELECT a customer 
--   WHERE:
--      whose date of birth makes them 15-17 years old
--        so that the results include all movies except those classified �R�

--***** Please note: I have limited the result to a single customer as the sub query requirements stated: SELECT a customer
--*****              if we wanted to return all customers that suit between the age limit, I would remove the customer email where clause in the sub query

SELECT		dbo.Movies.movieName, dbo.Movies.movieDuration, dbo.Movies.movieDescription
FROM		dbo.Movies INNER JOIN
				dbo.Classifications ON dbo.Movies.classification = dbo.Classifications.classification
WHERE		(CAST(CASE dbo.Classifications.classificationMinimumAge WHEN 'Not Applicable' THEN '0' ELSE classificationMinimumAge END AS int) <=
                             (SELECT	FLOOR(DATEDIFF(DAY, customerDOB, GETDATE()) / 365.25) AS Age
                              FROM		dbo.Customers
                              WHERE		(customerEmail = '[email protected]') AND (FLOOR(DATEDIFF(DAY, customerDOB, GETDATE()) / 365.25) IN (15, 16, 17))));



-- Query 9 � Session Revenue
-- SELECT session ID, session date/time, movie name, cinema name, tickets sold and total revenue of all sessions that occurred in the past
--    Total revenue is the session cost multiplied by the number of tickets sold
--    Ensure that sessions that had no tickets sold appear in the results (with 0 tickets sold and 0 revenue)
-- Order the results by total revenue, in descending order

SELECT		dbo.vSession.sessionId, 
			dbo.vSession.sessionDateTime, 
			dbo.vSession.movieName, 
			dbo.vSession.cinemaName, 
			SUM(ISNULL(dbo.TicketPurchases.ticketPurchaseNumberPurchased, 0)) AS TotalTicketsSold, 
			ISNULL(dbo.TicketPurchases.ticketPurchaseNumberPurchased * dbo.vSession.sessionTicketCost, 0) AS TotalTicketRevenue
FROM		dbo.vSession LEFT OUTER JOIN
				dbo.TicketPurchases ON dbo.vSession.sessionId = dbo.TicketPurchases.sessionId
GROUP BY	dbo.vSession.sessionId, 
			dbo.vSession.sessionDateTime, 
			dbo.vSession.movieName, 
			dbo.vSession.cinemaName, 
			ISNULL(dbo.TicketPurchases.ticketPurchaseNumberPurchased * dbo.vSession.sessionTicketCost, 0)
ORDER BY	ISNULL(dbo.TicketPurchases.ticketPurchaseNumberPurchased * dbo.vSession.sessionTicketCost, 0) DESC;

3. 创建视图


USE MovieTheatre;
GO

-- Cinema View 
-- Create a view that selects the cinema ID number, cinema name, seating capacity and the name of the cinema type for all cinemas

DROP VIEW IF EXISTS vCinema
GO
CREATE VIEW vCinema AS
SELECT	dbo.Cinemas.cinemaId, 
		dbo.Cinemas.cinemaName, 
		dbo.Cinemas.cinemaSeatingCapacity, 
		dbo.CinemasTypes.cinemaTypeName
FROM	dbo.Cinemas INNER JOIN
			dbo.CinemasTypes ON dbo.Cinemas.cinemaTypeId = dbo.CinemasTypes.cinemaTypeId;
GO


-- Session View 
-- Create a view that selects the following details of all rows in the “session” table:
--		The session ID number, session date/time and cost of the session.
--		The movie ID number, movie name and classification of the movie (e.g. “PG”) being shown.
--		The cinema ID number, cinema name, seating capacity and cinema type name of the cinema that the session is in.

DROP VIEW IF EXISTS vSession
GO
CREATE VIEW vSession AS
SELECT	dbo.MovieSessions.sessionId, 
		dbo.MovieSessions.sessionDateTime, 
		dbo.MovieSessions.sessionTicketCost, 
		dbo.MovieSessions.movieId, 
		dbo.Movies.movieName, 
		dbo.Movies.classification, 
		dbo.vCinema.cinemaId, 
		dbo.vCinema.cinemaName, 
		dbo.vCinema.cinemaSeatingCapacity, 
		dbo.vCinema.cinemaTypeName
FROM	dbo.vCinema INNER JOIN
			dbo.MovieSessions ON dbo.vCinema.cinemaId = dbo.MovieSessions.cinemaId INNER JOIN
			dbo.Movies ON dbo.MovieSessions.movieId = dbo.Movies.movieId;
GO

猜你喜欢

转载自blog.csdn.net/Artificial_idiots/article/details/122096252
今日推荐