Move to B.Sc. folder

This commit is contained in:
Andrew Trieu
2024-01-17 11:03:31 +02:00
committed by Andrew Trieu
parent 6ee81b8321
commit f920ce3ec5
1830 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,10 @@
CREATE INDEX RankingIndex ON Ranking(FK_playerid);
CREATE INDEX PlayerIndex1 ON MatchesWithNames(PlayerOne);
CREATE INDEX PlayerIndex2 ON MatchesWithNames(PlayerTwo);
CREATE INDEX PlayerIndex3 ON MatchesWithNames(Winner);
CREATE INDEX PLayerIndex4 ON Player(playerid);
SELECT PlayerOne, PlayerTwo, resultSets, Winner, rank AS 'Winner rank', points AS 'Winner points', record AS 'Winner record' FROM MatchesWithNames
INNER JOIN Player P1 ON (P1.first_name || ' ' || P1.last_name) = Winner
INNER JOIN Ranking ON P1.playerid = Ranking.FK_playerid
LIMIT 3500;

View File

@@ -0,0 +1,22 @@
SELECT M1.resultSets, M1.matchdate, P1.first_name || ' ' || P1.last_name AS PlayerOne, P1.nationality, R1.rank, R1.points,
P2.first_name || ' ' || P2.last_name AS PlayerTwo, P2.nationality, R2.rank, R2.points
FROM Matches M1, Matches M2, Player P1, Player P2, Player P3, Ranking R1, Ranking R2, Ranking R3
WHERE P1.playerid = M1.FK_playerOne AND P2.playerid = M1.FK_playerTwo AND M1.winnerID = P3.playerid
AND P1.playerid = R1.FK_playerid AND P2.playerid = R2.FK_playerid AND P3.playerid = R3.FK_playerid
AND P1.first_name != P2.first_name AND P1.nationality != P2.nationality
AND M1.winnerID NOT IN (SELECT playerid FROM Player, Matches
WHERE playerid = FK_playerOne OR playerid = FK_playerTwo
GROUP BY playerid HAVING COUNT(*) < (SELECT MAX(count)-5 FROM
(SELECT COUNT(*) AS count FROM Player, Matches
WHERE playerid = FK_playerOne OR playerid = FK_playerTwo
GROUP BY playerid) AS counts)
) AND M1.winnerID NOT IN (SELECT playerid FROM Player, Matches
WHERE playerid != winnerID AND (playerid = FK_playerOne OR playerid = FK_playerTwo)
GROUP BY playerid HAVING COUNT (*) = (SELECT MIN (count) FROM
(SELECT COUNT(*) as count FROM Player, Matches
WHERE playerid != winnerID AND (playerid = FK_playerOne OR playerid = FK_playerTwo)
GROUP BY playerid) AS counts)) AND M1.winnerID IN ( SELECT winnerID FROM Matches GROUP BY winnerID HAVING COUNT(*) >
(SELECT AVG (count) FROM (SELECT COUNT(*) AS count FROM Matches GROUP BY winnerID) AS counts)
) AND NOT ( NOT EXISTS (SELECT M1.FK_playerOne FROM Matches M3, Matches M4 WHERE M3.matchid != M4.matchid AND M3.matchdate = M4.matchdate
AND (M3.FK_playerOne = M4.FK_playerOne OR M3.FK_playerTwo = M4.FK_playerOne OR M3.FK_playerTwo = M4.FK_playerOne OR M3.FK_playerTwo = M4.FK_playerTwo))
) AND length(M1.resultSets) > 17 GROUP BY M1.matchid;

View File

@@ -0,0 +1,2 @@
SELECT Matches.matchid, Matches.FK_playerOne, Matches.FK_playerTwo, Player.playerid, Player.last_name FROM Matches
JOIN Player ON Matches.FK_playerOne=Player.playerid

View File

@@ -0,0 +1,109 @@
CREATE TABLE "Customer" (
"CustomerID" INTEGER NOT NULL,
"Name" TEXT,
"Age" INTEGER,
PRIMARY KEY("CustomerID")
);
CREATE TABLE "Address" (
"AddressID" INTEGER NOT NULL,
"CustomerID" INTEGER NOT NULL,
"Street" TEXT,
"Number" INTEGER,
"PostalCode" INTEGER,
"Region" TEXT,
"CountryID" INTEGER NOT NULL,
CONSTRAINT FK_CustomerID
FOREIGN KEY("CustomerID") REFERENCES "Customer"("CustomerID")
ON DELETE CASCADE,
CONSTRAINT FK_CountryID
FOREIGN KEY("CountryID") REFERENCES "Country"("CountryID")
ON DELETE CASCADE,
PRIMARY KEY("AddressID")
);
CREATE TABLE "Country" (
"CountryID" INTEGER NOT NULL,
"Country" TEXT,
PRIMARY KEY("CountryID")
);
CREATE TABLE "Contact" (
"ContactID" INTEGER NOT NULL,
"CustomerID" INTEGER NOT NULL,
"Phone" TEXT,
"Mail" TEXT,
PRIMARY KEY("ContactID"),
CONSTRAINT FK_CustomerID
FOREIGN KEY("CustomerID") REFERENCES "Customer"("CustomerID")
ON DELETE CASCADE
);
CREATE TABLE "Shipment" (
"OrderID" INTEGER NOT NULL,
"CustomerID" INTEGER NOT NULL,
"Date" TEXT,
PRIMARY KEY("OrderID"),
CONSTRAINT FK_CustomerID
FOREIGN KEY("CustomerID") REFERENCES "Customer"("CustomerID")
ON DELETE CASCADE
);
CREATE TABLE "Item" (
"ItemID" INTEGER NOT NULL,
"OrderID" INTEGER NOT NULL,
"Name" TEXT,
CONSTRAINT FK_OrderID
FOREIGN KEY("OrderID") REFERENCES "Shipment"("OrderID")
ON DELETE CASCADE,
PRIMARY KEY("ItemID")
);
INSERT INTO Customer VALUES
(10001,"Tomasz Gorczyca",23),
(10002,"Leon Kulikowski",36),
(10003,"Artur Nowak",32),
(10004,"Iwa Cegielska",28),
(10005,"Adriana Polkowska",31),
(10006,"Patrycja Ptaszynska",29);
INSERT INTO Country VALUES
(1,"Czechia"),
(2,"Slovakia");
INSERT INTO Address VALUES
(100,10003,"Bílokostelecká",77,46331,"Liberec",1),
(102,10005,"Kyselská",167,41801,"Teplice",1),
(103,10001,"Strmá",184,33701,"Rokycany",1),
(104,10004,"Mjr. Archipova",1,26012,"Dolný Kubín",2),
(105,10002,"Rybka",84,34092,"Ružomberok",2),
(106,10006,"Kurtaserskou",136,93201," Veľký Meder",2);
INSERT INTO Contact VALUES
(1, 10001, "+420778756417","sveta4521@badutstore.com"),
(2, 10002, "+421903443108","kimkjersteen@texasaol.com"),
(3, 10003, "+420776121001","shiknikolai@eloltsf.com"),
(4, 10004, "+421066229393","pebkac59@supermantutivie.com"),
(5, 10005, "+420771019248","thodoan@lohpcn.com"),
(6, 10006, "+421907353718","kotimur@playfuny.com");
INSERT INTO Shipment VALUES
(1001,10002,"11/12/2021"),
(1002,10006,"01/01/2022"),
(1003,10001,"05/02/2022"),
(1004,10001,"07/08/2021"),
(1005,10003,"09/11/2021"),
(1006,10005,"16/01/2022"),
(1007,10003,"17/01/2022"),
(1008,10004,"25/12/2021");
INSERT INTO Item VALUES
(1000001,1002,"Liquorice"),
(1000002,1002,"Surströmming"),
(1000003,1002,"Durian"),
(1000004,1004,"Frog"),
(1000005,1006,"Maggot Cheese"),
(1000006,1005,"Balut"),
(1000007,1002,"Blood sausage"),
(1000008,1001,"Vodka"),
(1000009,1005,"Coconut"),
(1000010,1006,"Escargots snail"),
(1000011,1004,"Tarantula"),
(1000012,1002,"Brain curry"),
(1000013,1001,"Chicken feet"),
(1000014,1003,"Hakarl"),
(1000015,1004,"Basashi"),
(1000016,1002,"Molokhia"),
(1000017,1004,"Civet coffee"),
(1000018,1006,"Stinky tofu");

View File

@@ -0,0 +1,8 @@
SELECT
(select first_name||" "||last_name from Player where Matches.FK_playerOne=playerid) as "Player one",
(select first_name||" "||last_name from Player where Matches.FK_playerTwo=playerid) as "Player two",
Matches.matchdate as Matchdate,
(select first_name||" "||last_name from Player where Matches.winnerID=playerid) as Winner
From Matches
GROUP BY FK_playerOne,FK_playerTwo HAVING count(*)>1
ORDER BY Matches.matchdate

View File

@@ -0,0 +1,2 @@
SELECT * FROM Player, Ranking
WHERE rank <= 10 AND playerid = rankingid;

View File

@@ -0,0 +1,2 @@
INSERT INTO Player VALUES (31, "Emil","Ruusuvuori", "FIN", "02/04/1999");
INSERT INTO Ranking VALUES (31,0,31,"W: 0 - L: 0",31)

View File

@@ -0,0 +1,2 @@
SELECT *, count(*) as qty FROM Matches
GROUP BY FK_playerOne, FK_playerTwo HAVING count(*)>1

View File

@@ -0,0 +1,169 @@
CREATE TABLE "User" (
"UserID" INTEGER NOT NULL,
"Username" TEXT,
"Verified" TEXT,
"Followers" INTEGER,
PRIMARY KEY("UserID")
);
CREATE TABLE "Tweet" (
"TweetID" INTEGER NOT NULL,
"UserID" INTEGER NOT NULL,
"Content" TEXT,
CONSTRAINT FK_UserID
FOREIGN KEY("UserID") REFERENCES "User"("UserID")
ON DELETE CASCADE,
PRIMARY KEY("TweetID")
);
CREATE TABLE "Comments" (
"CommentID" INTEGER NOT NULL,
"UserID" INTEGER NOT NULL,
"TweetID" INTEGER,
"FK_CommentID" INTEGER,
"Content" TEXT,
CONSTRAINT FK_UserID
FOREIGN KEY("UserID") REFERENCES "User"("UserID")
ON DELETE CASCADE,
CONSTRAINT FK_CommentID
FOREIGN KEY("FK_CommentID") REFERENCES "Comments"("CommentID")
ON DELETE CASCADE,
CONSTRAINT FK_TweetID
FOREIGN KEY("TweetID") REFERENCES "Tweet"("TweetID")
ON DELETE CASCADE,
PRIMARY KEY("CommentID")
);
CREATE TABLE "Likes" (
"LikeID" INTEGER NOT NULL,
"UserID" INTEGER NOT NULL,
"TweetID" INTEGER,
"CommentID" INTEGER,
PRIMARY KEY("LikeID"),
CONSTRAINT FK_UserID
FOREIGN KEY("UserID") REFERENCES "User"("UserID")
ON DELETE CASCADE,
CONSTRAINT FK_CommentID
FOREIGN KEY("CommentID") REFERENCES "Comments"("CommentID")
ON DELETE CASCADE,
CONSTRAINT FK_TweetID
FOREIGN KEY("TweetID") REFERENCES "Tweet"("TweetID")
ON DELETE CASCADE
);
CREATE TABLE "Hashtag" (
"HashtagID" INTEGER,
"Content" TEXT,
PRIMARY KEY("HashtagID")
);
CREATE TABLE "HashtagsInContent" (
"HashtagID" INTEGER NOT NULL,
"TweetID" INTEGER,
"CommentID" INTEGER,
CONSTRAINT FK_HashtagID
FOREIGN KEY("HashtagID") REFERENCES "Hashtag"("HashtagID")
ON DELETE CASCADE,
CONSTRAINT FK_TweetID
FOREIGN KEY("TweetID") REFERENCES "Tweet"("TweetID")
ON DELETE CASCADE,
CONSTRAINT FK_CommentID
FOREIGN KEY("CommentID") REFERENCES "Comments"("CommentID")
ON DELETE CASCADE
);
INSERT INTO User VALUES
(10001,"MelonHusk","true",22049),
(10002,"DonaldDuck","true",149195),
(10003,"KamKirl","false",207464),
(10004,"JustForLaughs","true",22019),
(10005,"TheRock","false",221749),
(10006,"ReynoldsFan","false",65449),
(10007,"SkullPoopL","false",6511789),
(10008,"PingFinity","true",5464198),
(10009,"HugeAckman","false",1981497),
(10010,"SnakeShot","true",47896);
INSERT INTO Tweet VALUES
(20001,10002,"Pretty sure that the world is just Duckburg"),
(20002,10003,"If you know what is good for you, you should do it."),
(20003,10004,"Why the good die young and the bad go to hell?"),
(20004,10005,"Having snow in your shoe is as much fun as having warm beer."),
(20005,10007,"Ice bucket challenge"),
(20006,10008,"Because science, right?"),
(20007,10009,"Did you know that the number of Nick Cage films correlate with drowning in pool?"),
(20008,10001,"Make sure you brush your hair before going to bed."),
(20009,10002,"Bear, beer, beard, bird, turd. Bears are made of poop."),
(20010,10010,"Rock 'n roll all night long with your best friends!");
INSERT INTO Comments VALUES
(30001,10002,20001,NULL,"And Scrooge is the richest living being in the world."),
(30002,10003,20002,NULL,"What if you don't know what is good for you? Do things to find out?"),
(30003,10004,20003,null,"Because hell has to fill the torturer positions first."),
(30004,10006,20004,null,"Or as fun as making out with a pillow."),
(30005,10007,null,30002,"No no no, you ask from others what is good for them."),
(30006,10008,null,30003,"This sounds like the typical corporate ladder, where the first ones become executives and managers."),
(30007,10009,null,30001,"Does Mickey Mouse live in Duckburg or Mouseton?"),
(30008,10008,null,30002,"Or never do anything so you don't accidentally do anything bad."),
(30009,10009,20008,null,"The new way to handle bedhair?"),
(30010,10010,20009,null,"I think you dropped the last screw from your brain.");
INSERT INTO Hashtag VALUES
(40001,"#win"),
(40002,"#friends"),
(40003,"#funny"),
(40004,"#giveaway"),
(40005,"#contest"),
(40006,"#thursdaythoughts"),
(40007,"#traveltuesday"),
(40008,"#science"),
(40009,"#fitness"),
(40010,"#goals");
INSERT INTO HashtagsInContent VALUES
(40001,20003,null),
(40002,20004,null),
(40003,20005,null),
(40004,20006,null),
(40005,null,30006),
(40006,null,30007),
(40007,null,30008),
(40008,null,30009),
(40009,null,30010),
(40010,20002,null),
(40003,20003,null),
(40004,null,30004),
(40005,20010,null),
(40006,20004,null),
(40008,null,30003),
(40009,null,30004),
(40010,null,30005);
INSERT INTO Likes VALUES
(50001,10010,20003,null),
(50002,10008,20005,null),
(50003,10005,null,30005),
(50004,10010,null,30007),
(50005,10007,20010,null),
(50006,10001,null,30007),
(50007,10003,null,30003),
(50008,10005,20009,null),
(50009,10009,20010,null),
(50010,10010,20010,null);
CREATE VIEW Comments_of_comments AS
SELECT (select Username from User where User.UserID=Comments.UserID) as User, Content as Comment, FK_CommentID as "Commented on" FROM Comments
WHERE FK_CommentID IS NOT NULL
ORDER BY User;
CREATE TRIGGER hashtag_not_allowed
BEFORE INSERT ON Hashtag
BEGIN
SELECT
CASE
WHEN (select NEW.Content from Hashtag) LIKE "%mayonnaise%" THEN
RAISE (ABORT,"Mayonnaise detected!")
END;
END;
CREATE VIEW Tweets_and_tags AS
SELECT (select Username from User where User.UserID=Tweet.UserID) as User,
Tweet.Content as Tweet, group_concat(Hashtag.Content,"") as Hashtag from Tweet
INNER JOIN HashtagsInContent ON HashtagsInContent.TweetID=Tweet.TweetID
INNER JOIN Hashtag ON HashtagsInContent.HashtagID=Hashtag.HashtagID
GROUP BY User;

View File

@@ -0,0 +1,70 @@
CREATE TABLE "User" (
"UserID" INTEGER NOT NULL,
"Username" TEXT,
"Verified" TEXT,
"Followers" INTEGER,
PRIMARY KEY("UserID")
);
CREATE TABLE "Tweet" (
"TweetID" INTEGER NOT NULL,
"UserID" INTEGER NOT NULL,
"Content" TEXT,
CONSTRAINT FK_UserID
FOREIGN KEY("UserID") REFERENCES "User"("UserID")
ON DELETE CASCADE,
PRIMARY KEY("TweetID")
);
CREATE TABLE "Comments" (
"CommentID" INTEGER NOT NULL,
"UserID" INTEGER NOT NULL,
"TweetID" INTEGER,
"FK_CommentID" INTEGER,
"Content" TEXT,
CONSTRAINT FK_UserID
FOREIGN KEY("UserID") REFERENCES "User"("UserID")
ON DELETE CASCADE,
CONSTRAINT FK_CommentID
FOREIGN KEY("FK_CommentID") REFERENCES "Comments"("CommentID")
ON DELETE CASCADE,
CONSTRAINT FK_TweetID
FOREIGN KEY("TweetID") REFERENCES "Tweet"("TweetID")
ON DELETE CASCADE,
PRIMARY KEY("CommentID")
);
CREATE TABLE "Likes" (
"LikeID" INTEGER NOT NULL,
"UserID" INTEGER NOT NULL,
"TweetID" INTEGER,
"CommentID" INTEGER,
PRIMARY KEY("LikeID"),
CONSTRAINT FK_UserID
FOREIGN KEY("UserID") REFERENCES "User"("UserID")
ON DELETE CASCADE,
CONSTRAINT FK_CommentID
FOREIGN KEY("CommentID") REFERENCES "Comments"("CommentID")
ON DELETE CASCADE,
CONSTRAINT FK_TweetID
FOREIGN KEY("TweetID") REFERENCES "Tweet"("TweetID")
ON DELETE CASCADE
);
CREATE TABLE "Hashtag" (
"HashtagID" INTEGER,
"Content" TEXT,
PRIMARY KEY("HashtagID")
);
CREATE TABLE "HashtagsInContent" (
"HashtagID" INTEGER NOT NULL,
"TweetID" INTEGER,
"CommentID" INTEGER,
CONSTRAINT FK_HashtagID
FOREIGN KEY("HashtagID") REFERENCES "Hashtag"("HashtagID")
ON DELETE CASCADE,
CONSTRAINT FK_TweetID
FOREIGN KEY("TweetID") REFERENCES "Tweet"("TweetID")
ON DELETE CASCADE,
CONSTRAINT FK_CommentID
FOREIGN KEY("CommentID") REFERENCES "Comments"("CommentID")
ON DELETE CASCADE
)

View File

@@ -0,0 +1,80 @@
INSERT INTO User VALUES
(10001,"MelonHusk",true,22049),
(10002,"DonaldDuck",true,149195),
(10003,"KamKirl",false,207464),
(10004,"JustForLaughs",true,22019),
(10005,"TheRock",false,221749),
(10006,"ReynoldsFan",false,65449),
(10007,"SkullPoopL",false,6511789),
(10008,"PingFinity",true,5464198),
(10009,"HugeAckman",false,1981497),
(10010,"SnakeShot",true,47896);
INSERT INTO Tweet VALUES
(20001,10002,"Pretty sure that the world is just Duckburg"),
(20002,10003,"If you know what is good for you, you should do it."),
(20003,10004,"Why the good die young and the bad go to hell?"),
(20004,10005,"Having snow in your shoe is as much fun as having warm beer."),
(20005,10007,"Ice bucket challenge"),
(20006,10008,"Because science, right?"),
(20007,10009,"Did you know that the number of Nick Cage films correlate with drowning in pool?"),
(20008,10001,"Make sure you brush your hair before going to bed."),
(20009,10002,"Bear, beer, beard, bird, turd. Bears are made of poop."),
(20010,10010,"Rock 'n roll all night long with your best friends!");
INSERT INTO Comments VALUES
(30001,10002,20001,NULL,"And Scrooge is the richest living being in the world."),
(30002,10003,20002,NULL,"What if you don't know what is good for you? Do things to find out?"),
(30003,10004,20003,null,"Because hell has to fill the torturer positions first."),
(30004,10006,20004,null,"Or as fun as making out with a pillow."),
(30005,10007,null,30002,"No no no, you ask from others what is good for them."),
(30006,10008,null,30003,"This sounds like the typical corporate ladder, where the first ones become executives and managers."),
(30007,10009,null,30001,"Does Mickey Mouse live in Duckburg or Mouseton?"),
(30008,10008,null,30002,"Or never do anything so you don't accidentally do anything bad."),
(30009,10009,20008,null,"The new way to handle bedhair?"),
(30010,10010,20009,null,"I think you dropped the last screw from your brain.");
INSERT INTO Hashtag VALUES
(40001,"#win"),
(40002,"#friends"),
(40003,"#funny"),
(40004,"#giveaway"),
(40005,"#contest"),
(40006,"#thursdaythoughts"),
(40007,"#traveltuesday"),
(40008,"#science"),
(40009,"#fitness"),
(40010,"#goals");
INSERT INTO HashtagsInContent VALUES
(40001,20003,null),
(40002,20004,null),
(40003,20005,null),
(40004,20006,null),
(40005,null,30006),
(40006,null,30007),
(40007,null,30008),
(40008,null,30009),
(40009,null,30010),
(40010,20002,null),
(40003,20003,null),
(40004,null,30004),
(40005,20010,null),
(40006,20004,null),
(40008,null,30003),
(40009,null,30004),
(40010,null,30005);
INSERT INTO Likes VALUES
(50001,10010,20003,null),
(50002,10008,20005,null),
(50003,10005,null,30005),
(50004,10010,null,30007),
(50005,10007,20010,null),
(50006,10001,null,30007),
(50007,10003,null,30003),
(50008,10005,20009,null),
(50009,10009,20010,null),
(50010,10010,20010,null);

View File

@@ -0,0 +1,4 @@
CREATE VIEW Comments_of_comments AS
SELECT (select Username from User where User.UserID=Comments.UserID) as User, Content as Comment, FK_CommentID as "Commented on" FROM Comments
WHERE FK_CommentID IS NOT NULL
ORDER BY User

View File

@@ -0,0 +1,9 @@
CREATE TRIGGER hashtag_not_allowed
BEFORE INSERT ON Hashtag
BEGIN
SELECT
CASE
WHEN (select NEW.Content from Hashtag) LIKE "%mayonnaise%" THEN
RAISE (ABORT,"Mayonnaise detected!")
END;
END;

View File

@@ -0,0 +1,6 @@
CREATE VIEW Tweets_and_tags AS
SELECT (select Username from User where User.UserID=Tweet.UserID) as User,
Tweet.Content as Tweet, group_concat(Hashtag.Content,"") as Hashtag from Tweet
INNER JOIN HashtagsInContent ON HashtagsInContent.TweetID=Tweet.TweetID
INNER JOIN Hashtag ON HashtagsInContent.HashtagID=Hashtag.HashtagID
GROUP BY User

View File

@@ -0,0 +1,18 @@
CREATE TABLE musicrecords (
band VARCHAR (50),
band_member VARCHAR (50),
member_instrument VARCHAR (50),
track VARCHAR (50),
track_duration VARCHAR (50),
album VARCHAR (50),
releaseYear INTEGER
);
CREATE VIEW View_1 AS
SELECT band, band_member, member_instrument FROM musicrecords
WHERE (band_member IS NOT NULL) AND (member_instrument IS NOT NULL);
CREATE VIEW View_2 AS
SELECT band, album, releaseYear FROM musicrecords
WHERE (album IS NOT NULL) AND (releaseYear IS NOT NULL);
CREATE VIEW View_3 AS
SELECT band, album, track, track_duration FROM musicrecords
WHERE (album IS NOT NULL) AND (track IS NOT NULL) AND (track_duration IS NOT NULL);

View File

@@ -0,0 +1,153 @@
####################################################
############## Do not touch this part ##############
import sqlite3
db = sqlite3.connect('hw5tennis.db')
cur = db.cursor()
def initializeDB():
try:
f = open("sqlcommands.sql", "r")
commandstring = ""
for line in f.readlines():
commandstring += line
cur.executescript(commandstring)
except sqlite3.OperationalError:
print("Database exists, skip initialization")
except:
print("No SQL file to be used for initialization")
def main():
initializeDB()
userInput = -1
while(userInput != "0"):
print("\nMenu options:")
print("1: Print Players")
print("2: Print Ranking")
print("3: Print Matches")
print("4: Search for one player")
print("5: Move matchdate")
print("6: Delete player")
print("0: Quit")
userInput = input("What do you want to do? ")
print(userInput)
if userInput == "1":
printPlayers()
if userInput == "2":
printRanking()
if userInput == "3":
printMatches()
if userInput == "4":
searchPlayer()
if userInput == "5":
moveMatch()
if userInput == "6":
deletePlayer()
if userInput == "0":
print("Ending software...")
db.close()
return
############## Do not touch part ends ##############
####################################################
############## Please modify the following ##############
def printPlayers():
print("Printing players")
"""
Insert the correct Python and SQL commands
to print all players
"""
# Start your modifications after this comment
cur.execute("SELECT * FROM Player")
for i in cur.fetchall():
print(i)
return
def printRanking():
print("Printing ranking")
"""
Insert the correct Python and SQL commands
to print all ranking information
"""
# Start your modifications after this comment
cur.execute("SELECT * FROM Ranking")
for i in cur.fetchall():
print(i)
return
def printMatches():
print("Printing matches")
"""
Insert the correct Python and SQL commands
to print all ranking information
"""
# Start your modifications after this comment
cur.execute("SELECT * FROM Matches")
for i in cur.fetchall():
print(i)
return
def searchPlayer():
playerName = input("What is the player's surname? ")
"""
Insert the correct Python and SQL commands to find the player
using the given surname
"""
# Start your modifications after this comment
cur.execute("SELECT * FROM Player WHERE last_name = '%s'" % playerName)
info = cur.fetchall()[0]
print("ID: "+str(info[0]))
print("First name: "+str(info[1]))
print("Last name: "+str(info[2]))
print("Birthdate: "+str(info[4]))
print("Nationality:"+str(info[3]))
return
def moveMatch():
matchID = input("What is the matchID of the match you want to move? ")
newMatchDate = input("What is the new matchdate you want to set?")
"""
Using the correct Python and SQL comands:
Change the match date based on the given matchID and new matchdate
IF a new matchdate is set to NULL, set the winner and result to NULL as well
"""
# Start your modifications after this comment
if newMatchDate == 'NULL':
cur.execute("UPDATE Matches SET resultSets = %s, winnerID = %s, matchdate = %s WHERE matchID = %s" %
('NULL', 'NULL', 'NULL', matchID))
else:
cur.execute("UPDATE Matches SET matchdate = '%s' WHERE matchID = %s" %
(newMatchDate, matchID))
db.commit()
return
def deletePlayer():
playerID = input("What is the player's PlayerID? ")
"""
Using the correct Python and SQL comands:
Delete the Player and his Ranking information
Additionally, set the playerid to NULL in ALL match-data it is found
"""
# Start your modifications after this comment
cur.execute("DELETE FROM Player WHERE playerid = %s" % playerID)
cur.execute("DELETE FROM Ranking WHERE FK_playerid = %s" % playerID)
cur.execute(
"UPDATE Matches SET FK_playerOne = NULL WHERE FK_playerOne = %s" % playerID)
cur.execute(
"UPDATE Matches SET FK_playerTwo = NULL WHERE FK_playerTwo = %s" % playerID)
cur.execute(
"UPDATE Matches SET winnerID = NULL WHERE winnerID = %s" % playerID)
db.commit()
main()

View File

@@ -0,0 +1,3 @@
CREATE INDEX PlayerIndex ON Player(playerid);
CREATE INDEX MatchesIndex ON Matches(FK_playerOne,FK_playerTwo, winnerID);
CREATE INDEX RankingIndex ON Ranking(FK_playerid);

View File

@@ -0,0 +1,11 @@
TweetID,UserID,Content
20001,10002,Pretty sure that the world is just Duckburg
20002,10003,"If you know what is good for you, you should do it."
20003,10004,Why the good die young and the bad go to hell?
20004,10005,Having snow in your shoe is as much fun as having warm beer.
20005,10007,Ice bucket challenge
20006,10008,"Because science, right?"
20007,10009,Did you know that the number of Nick Cage films correlate with drowning in pool?
20008,10001,Make sure you brush your hair before going to bed.
20009,10002,"Bear, beer, beard, bird, turd. Bears are made of poop."
20010,10010,Rock 'n roll all night long with your best friends!
1 TweetID UserID Content
2 20001 10002 Pretty sure that the world is just Duckburg
3 20002 10003 If you know what is good for you, you should do it.
4 20003 10004 Why the good die young and the bad go to hell?
5 20004 10005 Having snow in your shoe is as much fun as having warm beer.
6 20005 10007 Ice bucket challenge
7 20006 10008 Because science, right?
8 20007 10009 Did you know that the number of Nick Cage films correlate with drowning in pool?
9 20008 10001 Make sure you brush your hair before going to bed.
10 20009 10002 Bear, beer, beard, bird, turd. Bears are made of poop.
11 20010 10010 Rock 'n roll all night long with your best friends!

View File

@@ -0,0 +1,17 @@
SELECT (select first_name||" "||last_name from Player where Matches.winnerid=playerid) as "Winner",
(select FK_playerid from Ranking where Matches.winnerid=Ranking.FK_playerid) As "Winner rank",
CASE
WHEN Matches.winnerid==Matches.FK_playerOne
THEN (select first_name||" "||last_name from Player where Matches.FK_playerTwo=playerid)
ELSE
(select first_name||" "||last_name from Player where Matches.FK_playerOne=playerid)
END as "Loser",
CASE
WHEN Matches.winnerid==Matches.FK_playerOne
THEN (select FK_playerid from Ranking where Matches.FK_playerTwo=Ranking.FK_playerid)
ELSE
(select FK_playerid from Ranking where Matches.FK_playerOne=Ranking.FK_playerid)
END as "Loser rank",
matchdate as Matchdate
FROM Matches WHERE "Loser rank"<6
ORDER BY "Winner rank"

View File

@@ -0,0 +1,11 @@
<!doctype html>
<html>
<head>
<title>Homework 2 instructions, total worth 11 + 2 %</title>
<meta charset="utf-8">
</head>
<body>
<p dir="ltr" style="text-align: left;"></p><p dir="ltr">Beneath you will find a database diagram for the database you are accessing.&nbsp;</p><p dir="ltr"><br></p><p dir="ltr"><img src="data/tennisdiagram.png" alt="" role="presentation"></p><p dir="ltr"><br></p><p dir="ltr">All primary keys automatically increment and you should&nbsp;<strong>NOT</strong>&nbsp;insert them yourself. <strong><span class="" style="color: rgb(239, 69, 64);">Return each assignment as .sql file. If you use the built-in testing ground, make sure the file you name has .sql at the end.</span>&nbsp;</strong><br>Your task is to do the following:</p><p dir="ltr"></p><p></p><ol><li>Print all players and their information</li><li>Print all player and ranking information of players in the top 10 ranking</li><li>Change all Spanish players to be from Portugal (abbreviation: POR).</li><li>Add a new match between the first rank and last rank, where result is "0-0", match date is "unplayed" and winner is 0.</li><li>Add a new player "Emil Ruusuvuori" from Finland (abbreviation: FIN), born 02/04/1999. Give him a new ranking at position 31 with 0 points and a record of "W: 0 - L: 0"</li></ol><p>Here are some harder queries:</p><ol><li>Print all matches where the same players have faced off more than once against each other as well as the name of the winner of each match. <strong>Order the results by the match date.</strong><br>Use the following example columns and their respective data:<br><strong><span>|</span><u>&nbsp;</u><em>Player one</em><span>&nbsp;|</span>&nbsp;<em>Player two</em>&nbsp;<span>|</span>&nbsp;<em>Matchdate&nbsp;</em><span>|</span>&nbsp;<em>Winner</em>&nbsp;</strong><span><u><strong>|</strong></u><br><span><span class="" style="background-color: rgb(255, 255, 255); color: rgb(239, 69, 64);"><strong><span class="" style="color: rgb(51, 51, 51);">Add the following command to the beginning of your SQL Statement</span></strong><strong><span class="" style="color: rgb(51, 51, 51);">:</span> </strong><span style="font-weight: bold;">.headers on</span></span><br><span class="" style="background-color: rgb(255, 255, 255); color: rgb(239, 69, 64);"><strong>This enables SQLite to show the headers of your query.</strong></span></span><br></span>"Player one" and "Player two" columns should contain first and last name of each player.</li><li>Print all the matches the top 5 ranked players have lost in the following format and order the results by winner rank:<br><strong><u><span>|</span>&nbsp;<i>Winner name&nbsp;</i><span>|&nbsp;</span><em>Winner rank</em><span>&nbsp;|</span>&nbsp;<em>Loser name&nbsp;</em><span>|&nbsp;</span><i>Loser rank&nbsp;</i><span>|</span>&nbsp;<em>Matchdate&nbsp;</em><span>|</span></u>&nbsp;</strong><br><strong><span class="" style="color: rgb(239, 69, 64);"><span class="" style="color: rgb(51, 51, 51);">Add the following command to the beginning of your SQL Statement</span>: .headers on</span><br><span class="" style="color: rgb(239, 69, 64);">This enables SQLite to show the headers of your query.</span></strong><br><br></li></ol><p></p>
</body>
</html>

View File

@@ -0,0 +1,11 @@
<!doctype html>
<html>
<head>
<title>Homework 3 instructions</title>
<meta charset="utf-8">
</head>
<body>
<p dir="ltr" style="text-align: left;"></p><p dir="ltr">Your task is the following:<br></p><ol><li><strong>(1 %) Create an SQL database using the following data model:<br></strong><img src="data/Basic%20of%20DB%20ex%201-Page-4.drawio.png" alt="" role="presentation"><br><br><u>Remember to use PRIMARY KEY and FOREIGN KEY constraints.&nbsp;</u><br><br></li><li><strong><strong>(2 %)&nbsp;</strong>Create INSERT commands to insert the data given in the excel file within Topic 4 -section.<br></strong><br><strong><span>--- After this point, you can return the assignment at any time for some points if you do not want to do the rest of the homework. Jump to step 7.</span><br></strong><br></li><li><strong><strong><strong>(1 %)&nbsp;</strong></strong>Add ON DELETE CASCADE to all foreign key constraints.</strong></li><li><strong><strong><strong><strong><strong><strong>(2 %)</strong></strong></strong></strong>Create a view&nbsp;<span class="" style="color: rgb(152, 202, 62);">Comments_of_comments</span>&nbsp;that shows only comments associated with other comments in the following format and order the results by username:</strong><br><strong><span class="" style="color: rgb(239, 69, 64);">|User|Comment| Commented on |</span></strong><br></strong></li><li><strong><strong><strong><strong>(1 + 1 %)&nbsp;</strong></strong></strong>Create a trigger <span class="" style="color: rgb(152, 202, 62);">hashtag_not_allowed</span> that triggers before data is inserted into Hashtag- table. The trigger should raise an abort printing "Mayonnaise detected!" when hashtag content has the word <span class="" style="color: rgb(152, 202, 62);">mayonnaise</span></strong></li><li><strong><strong><strong><strong><strong>(1 + 1 %)&nbsp;</strong></strong></strong></strong>Create a view <span class="" style="color: rgb(152, 202, 62);">Tweets_and_tags</span>&nbsp;that shows all hashtags with the associated Tweet in the following format <strong><strong>and order the results by username</strong></strong>:</strong><br><strong><span class="" style="color: rgb(239, 69, 64);">|User|Tweet| Hashtag|</span></strong></li><li><strong>Return the sql statements for in one file.&nbsp;<span>Remember to have them in correct order so a table or entity does not reference something that does not yet exist.</span></strong></li></ol><br><br><br><br><br><p></p>
</body>
</html>

View File

@@ -0,0 +1,135 @@
####################################################
############## Do not touch this part ##############
import sqlite3
db = sqlite3.connect('hw5tennis.db')
cur = db.cursor()
def initializeDB():
try:
f = open("sqlcommands.sql", "r")
commandstring = ""
for line in f.readlines():
commandstring+=line
cur.executescript(commandstring)
except sqlite3.OperationalError:
print("Database exists, skip initialization")
except:
print("No SQL file to be used for initialization")
def main():
initializeDB()
userInput = -1
while(userInput != "0"):
print("\nMenu options:")
print("1: Print Players")
print("2: Print Ranking")
print("3: Print Matches")
print("4: Search for one player")
print("5: Move matchdate")
print("6: Delete player")
print("0: Quit")
userInput = input("What do you want to do? ")
print(userInput)
if userInput == "1":
printPlayers()
if userInput == "2":
printRanking()
if userInput == "3":
printMatches()
if userInput == "4":
searchPlayer()
if userInput == "5":
moveMatch()
if userInput == "6":
deletePlayer()
if userInput == "0":
print("Ending software...")
db.close()
return
############## Do not touch part ends ##############
####################################################
############## Please modify the following ##############
def printPlayers():
print("Printing players")
"""
Insert the correct Python and SQL commands
to print all players
"""
#Start your modifications after this comment
return
def printRanking():
print("Printing ranking")
"""
Insert the correct Python and SQL commands
to print all ranking information
"""
#Start your modifications after this comment
cur.execute("SELECT * FROM Ranking");
print(cur.fetchall());
return
def printMatches():
print("Printing matches")
"""
Insert the correct Python and SQL commands
to print all ranking information
"""
#Start your modifications after this comment
return
def searchPlayer():
playerName = input("What is the player's surname? ")
"""
Insert the correct Python and SQL commands to find the player
using the given surname
"""
#Start your modifications after this comment
print("ID:")
print("First name:")
print("Last name:")
print("Birthdate: ")
print("Nationality:")
return
def moveMatch():
matchID = input("What is the matchID of the match you want to move? ")
newMatchDate = input ("What is the new matchdate you want to set?")
"""
Using the correct Python and SQL comands:
Change the match date based on the given matchID and new matchdate
IF a new matchdate is set to NULL, set the winner and result to NULL as well
"""
#Start your modifications after this comment
return
def deletePlayer():
playerID = input("What is the player's PlayerID? ")
"""
Using the correct Python and SQL comands:
Delete the Player and his Ranking information
Additionally, set the playerid to NULL in ALL match-data it is found
"""
#Start your modifications after this comment
main()

View File

@@ -0,0 +1,11 @@
<!doctype html>
<html>
<head>
<title>Homework 5 - Instructions</title>
<meta charset="utf-8">
</head>
<body>
<p dir="ltr" style="text-align: left;"></p><p dir="ltr">Beneath you will find a database diagram for the database you are accessing.&nbsp;</p><p dir="ltr"><br></p><p dir="ltr"><img src="data/tennisdiagram.png" alt="" role="presentation"></p><p dir="ltr"><br></p><p dir="ltr"><strong>Return your assignment as <span class="" style="color: rgb(255, 255, 255); background-color: rgb(239, 69, 64);">.py file.</span> If you use the built-in testing ground, make sure the file you name has .py at the end.&nbsp;</strong><br>Your task is to do the following:</p><p dir="ltr">You are given a Python template in the Topic 6: Python to fill that has the following functions:</p><p dir="ltr"></p><ol><li>def printPlayers()</li><li>def printRanking()</li><li>def printMatches()<br></li><li>def searchPlayer()<br></li><li>def moveMatch()<br></li><li>def deletePlayer()<br><span class="" style="color: rgb(239, 69, 64);"><span class="" style="color: rgb(255, 255, 255); background-color: rgb(239, 69, 64);">Note</span>:</span> The deletePlayer() assumes that moveMatch() has been done correctly.</li></ol><p>Your task is to fill the functions with the appropriate Python and SQL commands.&nbsp;<br><span class="" style="background-color: rgb(239, 69, 64); color: rgb(255, 255, 255);">First three are worth 1 %, fourth, fifth and sixth are worth 2 %</span>. Each function will have its own test case.</p><p></p>
</body>
</html>

View File

@@ -0,0 +1,54 @@
CREATE DATABASE Project;
CREATE TABLE "Customer" (
"CustomerID" INTEGER NOT NULL,
"Name" TEXT,
"Age" INTEGER,
PRIMARY KEY("CustomerID")
);
CREATE TABLE "Address" (
"AddressID" INTEGER NOT NULL,
"CustomerID" INTEGER NOT NULL,
"Street" TEXT,
"Number" INTEGER,
"PostalCode" INTEGER,
"Region" TEXT,
"CountryID" INTEGER NOT NULL,
CONSTRAINT FK_CustomerID
FOREIGN KEY("CustomerID") REFERENCES "Customer"("CustomerID")
ON DELETE CASCADE,
CONSTRAINT FK_CountryID
FOREIGN KEY("CountryID") REFERENCES "Country"("CountryID")
ON DELETE CASCADE,
PRIMARY KEY("AddressID")
);
CREATE TABLE "Country" (
"CountryID" INTEGER NOT NULL,
"Country" TEXT,
PRIMARY KEY("CountryID")
);
CREATE TABLE "Contact" (
"ContactID" INTEGER NOT NULL,
"CustomerID" INTEGER NOT NULL,
"Phone" TEXT,
"Mail" TEXT,
PRIMARY KEY("ContactID"),
CONSTRAINT FK_CustomerID
FOREIGN KEY("CustomerID") REFERENCES "Customer"("CustomerID")
ON DELETE CASCADE
);
CREATE TABLE "Shipment" (
"CustomerID" INTEGER NOT NULL,
"ItemID" INTEGER NOT NULL,
"Date" TEXT,
CONSTRAINT FK_ItemID
FOREIGN KEY("ItemID") REFERENCES "Item"("ItemID")
ON DELETE CASCADE,
CONSTRAINT FK_CustomerID
FOREIGN KEY("CustomerID") REFERENCES "Customer"("CustomerID")
ON DELETE CASCADE
);
CREATE TABLE "Item" (
"ItemID" INTEGER NOT NULL,
"Name" TEXT,
PRIMARY KEY("ItemID")
);

View File

@@ -0,0 +1,52 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bokeh Plot</title>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-3.0.2.min.js"></script>
<script type="text/javascript">
Bokeh.set_log_level("info");
</script>
</head>
<body>
<div id="a3ed5b52-0df3-4007-938f-5c6012e956c8" data-root-id="p1004" style="display: contents;"></div>
<script type="application/json" id="p1215">
{"14ecb273-a373-45b0-a890-2c9208400025":{"version":"3.0.2","title":"Bokeh Application","defs":[],"roots":[{"type":"object","name":"Figure","id":"p1004","attributes":{"width":700,"height":300,"sizing_mode":"scale_width","x_range":{"type":"object","name":"FactorRange","id":"p1014","attributes":{"factors":["Durian","Surstr\u00f6mming","Liquorice","Vodka","Balut","Civet coffee","Maggot Cheese","Blood sausage","Escargots snail","Tarantula","Frog","Chicken feet"]}},"y_range":{"type":"object","name":"Range1d","id":"p1016","attributes":{"end":9}},"x_scale":{"type":"object","name":"CategoricalScale","id":"p1018"},"y_scale":{"type":"object","name":"LinearScale","id":"p1020"},"title":{"type":"object","name":"Title","id":"p1007","attributes":{"text":"Counts"}},"renderers":[{"type":"object","name":"GlyphRenderer","id":"p1042","attributes":{"data_source":{"type":"object","name":"ColumnDataSource","id":"p1001","attributes":{"selected":{"type":"object","name":"Selection","id":"p1003","attributes":{"indices":[],"line_indices":[]}},"selection_policy":{"type":"object","name":"UnionRenderers","id":"p1002"},"data":{"type":"map","entries":[["x",["Liquorice","Maggot Cheese","Vodka","Blood sausage","Escargots snail","Balut","Tarantula","Frog","Civet coffee","Durian","Surstr\u00f6mming","Chicken feet"]],["y",[2,1,2,1,1,2,1,1,2,3,3,1]]]}}},"view":{"type":"object","name":"CDSView","id":"p1043","attributes":{"filter":{"type":"object","name":"AllIndices","id":"p1044"}}},"glyph":{"type":"object","name":"VBar","id":"p1039","attributes":{"x":{"type":"field","field":"x"},"width":{"type":"value","value":0.9},"top":{"type":"field","field":"y"},"line_color":{"type":"value","value":"#1f77b4"},"fill_color":{"type":"value","value":"#1f77b4"}}},"nonselection_glyph":{"type":"object","name":"VBar","id":"p1040","attributes":{"x":{"type":"field","field":"x"},"width":{"type":"value","value":0.9},"top":{"type":"field","field":"y"},"line_color":{"type":"value","value":"#1f77b4"},"line_alpha":{"type":"value","value":0.1},"fill_color":{"type":"value","value":"#1f77b4"},"fill_alpha":{"type":"value","value":0.1},"hatch_alpha":{"type":"value","value":0.1}}},"muted_glyph":{"type":"object","name":"VBar","id":"p1041","attributes":{"x":{"type":"field","field":"x"},"width":{"type":"value","value":0.9},"top":{"type":"field","field":"y"},"line_color":{"type":"value","value":"#1f77b4"},"line_alpha":{"type":"value","value":0.2},"fill_color":{"type":"value","value":"#1f77b4"},"fill_alpha":{"type":"value","value":0.2},"hatch_alpha":{"type":"value","value":0.2}}}}}],"toolbar":{"type":"object","name":"Toolbar","id":"p1011"},"toolbar_location":null,"left":[{"type":"object","name":"LinearAxis","id":"p1028","attributes":{"ticker":{"type":"object","name":"BasicTicker","id":"p1029","attributes":{"mantissas":[1,2,5]}},"formatter":{"type":"object","name":"BasicTickFormatter","id":"p1030"},"major_label_policy":{"type":"object","name":"AllLabels","id":"p1031"}}}],"below":[{"type":"object","name":"CategoricalAxis","id":"p1022","attributes":{"ticker":{"type":"object","name":"CategoricalTicker","id":"p1023"},"formatter":{"type":"object","name":"CategoricalTickFormatter","id":"p1024"},"major_label_policy":{"type":"object","name":"AllLabels","id":"p1025"}}}],"center":[{"type":"object","name":"Grid","id":"p1027","attributes":{"axis":{"id":"p1022"},"grid_line_color":null}},{"type":"object","name":"Grid","id":"p1034","attributes":{"dimension":1,"axis":{"id":"p1028"}}},{"type":"object","name":"Legend","id":"p1057","attributes":{"visible":false,"items":[{"type":"object","name":"LegendItem","id":"p1058","attributes":{"label":{"type":"field","field":"x"},"renderers":[{"id":"p1042"}]}}]}}]}}]}}
</script>
<script type="text/javascript">
(function() {
const fn = function() {
Bokeh.safely(function() {
(function(root) {
function embed_document(root) {
const docs_json = document.getElementById('p1215').textContent;
const render_items = [{"docid":"14ecb273-a373-45b0-a890-2c9208400025","roots":{"p1004":"a3ed5b52-0df3-4007-938f-5c6012e956c8"},"root_ids":["p1004"]}];
root.Bokeh.embed.embed_items(docs_json, render_items);
}
if (root.Bokeh !== undefined) {
embed_document(root);
} else {
let attempts = 0;
const timer = setInterval(function(root) {
if (root.Bokeh !== undefined) {
clearInterval(timer);
embed_document(root);
} else {
attempts++;
if (attempts > 100) {
clearInterval(timer);
console.log("Bokeh: ERROR: Unable to run BokehJS code because BokehJS library is missing");
}
}
}, 10, root)
}
})(window);
});
};
if (document.readyState != "loading") fn();
else document.addEventListener("DOMContentLoaded", fn);
})();
</script>
</body>
</html>

View File

@@ -0,0 +1,120 @@
CREATE DATABASE Project;
CREATE TABLE "Customer" (
"CustomerID" INTEGER NOT NULL,
"Name" TEXT,
"Age" INTEGER,
PRIMARY KEY("CustomerID")
);
CREATE TABLE "Address" (
"AddressID" INTEGER NOT NULL,
"CustomerID" INTEGER NOT NULL,
"Street" TEXT,
"Number" INTEGER,
"PostalCode" INTEGER,
"Region" TEXT,
"CountryID" INTEGER NOT NULL,
CONSTRAINT FK_CustomerID
FOREIGN KEY("CustomerID") REFERENCES "Customer"("CustomerID")
ON DELETE CASCADE,
CONSTRAINT FK_CountryID
FOREIGN KEY("CountryID") REFERENCES "Country"("CountryID")
ON DELETE CASCADE,
PRIMARY KEY("AddressID")
);
CREATE TABLE "Country" (
"CountryID" INTEGER NOT NULL,
"Country" TEXT,
PRIMARY KEY("CountryID")
);
CREATE TABLE "Contact" (
"ContactID" INTEGER NOT NULL,
"CustomerID" INTEGER NOT NULL,
"Phone" TEXT,
"Mail" TEXT,
PRIMARY KEY("ContactID"),
CONSTRAINT FK_CustomerID
FOREIGN KEY("CustomerID") REFERENCES "Customer"("CustomerID")
ON DELETE CASCADE
);
CREATE TABLE "Shipment" (
"CustomerID" INTEGER NOT NULL,
"ItemID" INTEGER NOT NULL,
"Date" TEXT,
CONSTRAINT FK_ItemID
FOREIGN KEY("ItemID") REFERENCES "Item"("ItemID")
ON DELETE CASCADE,
CONSTRAINT FK_CustomerID
FOREIGN KEY("CustomerID") REFERENCES "Customer"("CustomerID")
ON DELETE CASCADE
);
CREATE TABLE "Item" (
"ItemID" INTEGER NOT NULL,
"Name" TEXT,
PRIMARY KEY("ItemID")
);
INSERT INTO Customer VALUES
(10001,"Tomasz Gorczyca",23),
(10002,"Leon Kulikowski",36),
(10003,"Artur Nowak",32),
(10004,"Iwa Cegielska",28),
(10005,"Adriana Polkowska",31),
(10006,"Patrycja Ptaszynska",29);
INSERT INTO Country VALUES
(1,"Czechia"),
(2,"Slovakia");
INSERT INTO Address VALUES
(100,10003,"Bílokostelecká",77,46331,"Liberec",1),
(102,10005,"Kyselská",167,41801,"Teplice",1),
(103,10001,"Strmá",184,33701,"Rokycany",1),
(104,10004,"Mjr. Archipova",1,26012,"Dolný Kubín",2),
(105,10002,"Rybka",84,34092,"Ružomberok",2),
(106,10006,"Kurtaserskou",136,93201," Veľký Meder",2);
INSERT INTO Contact VALUES
(1, 10001, "+420778756417","sveta4521@badutstore.com"),
(2, 10002, "+421903443108","kimkjersteen@texasaol.com"),
(3, 10003, "+420776121001","shiknikolai@eloltsf.com"),
(4, 10004, "+421066229393","pebkac59@supermantutivie.com"),
(5, 10005, "+420771019248","thodoan@lohpcn.com"),
(6, 10006, "+421907353718","kotimur@playfuny.com");
INSERT INTO Item VALUES
(1000001,"Liquorice"),
(1000002,"Surströmming"),
(1000003,"Durian"),
(1000004,"Frog"),
(1000005,"Maggot Cheese"),
(1000006,"Balut"),
(1000007,"Blood sausage"),
(1000008,"Vodka"),
(1000009,"Coconut"),
(1000010,"Escargots snail"),
(1000011,"Tarantula"),
(1000012,"Brain curry"),
(1000013,"Chicken feet"),
(1000014,"Hakarl"),
(1000015,"Basashi"),
(1000016,"Molokhia"),
(1000017,"Civet coffee"),
(1000018,"Stinky tofu");
INSERT INTO Shipment VALUES
(10001,1000001,"15/12/2021"),
(10001,1000005,"11/12/2021"),
(10002,1000008,"01/01/2022"),
(10002,1000007,"11/01/2021"),
(10002,1000010,"11/12/2021"),
(10002,1000006,"02/01/2022"),
(10003,1000011,"05/02/2022"),
(10003,1000004,"07/08/2021"),
(10003,1000017,"04/11/2021"),
(10004,1000006,"12/01/2022"),
(10004,1000003,"17/01/2022"),
(10005,1000003,"25/12/2021"),
(10006,1000002,"09/02/2022"),
(10006,1000001,"11/08/2021"),
(10007,1000003,"15/11/2021"),
(10007,1000002,"18/01/2022"),
(10007,1000008,"19/01/2022"),
(10008,1000017,"21/12/2021"),
(10004,1000013,"10/01/2022"),
(10008,1000002,"25/12/2021");

View File

@@ -0,0 +1,263 @@
try:
from prettytable import PrettyTable
except ImportError:
auth = input(
'This Python script requires PrettyTable library. Please press ENTER.')
import os
os.system('pip install prettytable')
from prettytable import PrettyTable
try:
from bokeh.io import output_file, show
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
except ImportError:
import os
os.system('pip install bokeh')
from bokeh.io import output_file, show
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
import sys
import sqlite3
try:
sql = sqlite3.connect(
r"Project.db")
except:
print("\nDatabase not found!")
cursor = sql.cursor()
def back():
input('\nPress ENTER to return to main menu...')
main()
def header():
num_fields = len(cursor.description)
field_names = [i[0] for i in cursor.description]
return field_names
def showTables():
tablelist = []
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
maintable = PrettyTable(["Option", "Number"])
tablenames = cursor.fetchall()
for i in range(len(tablenames)):
a = [x.replace('(', "").replace(')', "").replace("'", "")
for x in tablenames[i]]
tablelist.append(str(a[0]))
maintable.add_row([a[0], i+1])
print(maintable)
return tablelist
# First query - View table
def viewTable():
try:
tablelist = showTables()
choiceTable = int(input("Select table to view: "))
cursor.execute("SELECT * FROM %s" % (tablelist[choiceTable-1]))
table = PrettyTable(header())
values = cursor.fetchall()
for i in values:
a = [x.replace('(', "").replace(')', "").replace("'", "")
for x in str(i).split(',')]
table.add_row(a)
print(table)
except Exception as e:
print('\n'+str(e).capitalize())
back()
# Second query - Insert row
def insertRow():
try:
insert = []
tablelist = showTables()
choiceTable = int(input("Select table to insert values: "))
cursor.execute("SELECT * FROM %s" % (tablelist[choiceTable-1]))
scriptmain = "INSERT INTO %s VALUES " % tablelist[choiceTable-1]
multi = len(header())-1
scriptmain = scriptmain + '('+'%s'+',%s'*multi+')'
for i in header():
inp = input(i + " = ")
if inp.isnumeric() == True:
inp = int(inp)
else:
inp = "'"+inp+"'"
insert.append(inp)
insert = tuple(insert)
cursor.execute(scriptmain % (insert))
sql.commit()
except Exception as e:
print('\n'+str(e).capitalize())
sql.rollback()
back()
# Third query - Delete row
def deleteRow():
try:
tablelist = showTables()
choiceTable = int(input("Select table to delete values: "))
cursor.execute("SELECT * FROM %s" % (tablelist[choiceTable-1]))
scriptmain = "DELETE FROM %s WHERE" % (tablelist[choiceTable-1])
table = PrettyTable(["Option", "Number"])
count = 1
for i in header():
table.add_row([i, count])
count += 1
print(table)
choiceColumn = int(input("Select column to delete values: "))
column = header()[choiceColumn-1]
choiceField = input(column + " = ")
if choiceField.isnumeric() == True:
choiceField = int(choiceField)
else:
choiceField = "'"+choiceField+"'"
scriptmain = scriptmain + ' %s = %s'
cursor.execute(scriptmain % (column, choiceField))
sql.commit()
except Exception as e:
print('\n'+str(e).capitalize())
sql.rollback()
back()
# Fourth query - Update row
def updateRow():
try:
tablelist = showTables()
choiceTable = int(input("Select table to update values: "))
cursor.execute("SELECT * FROM %s" % (tablelist[choiceTable-1]))
scriptmain = "UPDATE " + (tablelist[choiceTable-1]) + " SET %s WHERE "
table = PrettyTable(["Option", "Number"])
count = 1
for i in header():
table.add_row([i, count])
count += 1
print(table)
choiceColumn = int(input("Select condition column: "))
column = header()[choiceColumn-1]
contentColumn = input(column + " = ")
if contentColumn.isnumeric() == True:
column = column + " = " + str(contentColumn)
else:
column = column + " = " + "'"+contentColumn + "'"
scriptmain = scriptmain + column
upd = ''
while True:
choiceField = int(input("Select column to be updated: "))
field = header()[choiceField-1]
contentField = input(field + " = ")
if contentField.isnumeric() == True:
field = field + " = " + str(contentField)
else:
field = field + " = " + "'"+contentField + "'"
upd = upd+", "+field
con = input(
'Do you want to add another one to be updated? (y for yes, any other key for no) ')
if con == 'y':
continue
else:
break
upd = upd[2:]
cursor.execute(scriptmain % upd)
sql.commit()
except Exception as e:
print('\n'+str(e).capitalize())
sql.rollback()
back()
# Fifth query - Bokeh visualization
def bokeh():
try:
lst = []
cursor.execute(
"SELECT Item.Name as Item from Shipment INNER JOIN Item on Shipment.ItemID=Item.ItemID ")
items = cursor.fetchall()
for i in items:
i = str(i).replace('(', '').replace(')', '').replace(
"'", "").replace(",", "")
lst.append(i)
order = [i for n, i in enumerate(lst) if i not in lst[:n]]
dct = {}
for i in order:
dct[i] = lst.count(i)
x = list(dct.keys())
y = list(dct.values())
sorted_x = sorted(x, key=lambda a: y[x.index(a)], reverse=True)
source = ColumnDataSource(data=dict(x=x, y=y))
p = figure(x_range=sorted_x, y_range=(0, 9), title="Counts",
toolbar_location=None, tools="", width=700, height=300, sizing_mode='scale_width')
p.vbar(x='x', top='y', width=0.9, legend_field='x', source=source)
p.xgrid.grid_line_color = None
p.legend.visible = False
output_file('BokehChart.html')
show(p)
back()
except Exception as e:
print('\n'+str(e).capitalize())
back()
# Sixth query - Many-to-many relation: 2 JOIN clauses
def itemCustomer():
try:
cursor.execute('SELECT Customer.Name as Customer, group_concat(Item.Name, ", ") as Item from Shipment INNER JOIN Customer on Shipment.CustomerID=Customer.CustomerID INNER JOIN Item on Item.ItemID=Shipment.ItemID GROUP BY Customer;')
table = PrettyTable(header())
final = cursor.fetchall()
for i in final:
table.add_row(list(i))
print(table)
except Exception as e:
print('\n'+str(e).capitalize())
back()
def main():
table = PrettyTable(["Option", "Number"])
table.add_row(['View Table', 1])
table.add_row(['Insert Row', 2])
table.add_row(['Delete Row', 3])
table.add_row(['Update Row', 4])
table.add_row(['Chart: Number of times each item was ordered', 5])
table.add_row(['List items each customer has ordered', 6])
table.add_row(['Quit', 7])
print(table)
option = input("Select option: ")
if option == '1':
viewTable()
elif option == '2':
insertRow()
elif option == '3':
deleteRow()
elif option == '4':
updateRow()
elif option == '5':
bokeh()
elif option == '6':
itemCustomer()
elif option == '7':
sql.close()
print("Thank you for using!")
sys.exit()
else:
print("\nUnknown option.")
back()
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,131 @@
# EX 1
winnings <-
100000 * 5 +
2000 * 40 +
1000 * 160 +
500 * 1000 +
30 * 16000 +
20 * 80000 +
10 * 180000 +
5 * 240000 +
4 * 250000
N <- 3000000
Expectation <- winnings / N
Expectation
# 2.44
# But one ticked costs 4 euros, so expected win is
Expectation - 4
# -1.56
# EX 2
dpois(0, lambda = 2.63) # a
dpois(1, lambda = 2.63) # b
dpois(2, lambda = 2.63) # c
dpois(3, lambda = 2.63) # d
dpois(4, lambda = 2.63) # e
1 - (dpois(0, lambda = 2.63) +
dpois(1, lambda = 2.63) +
dpois(2, lambda = 2.63) +
dpois(3, lambda = 2.63) +
dpois(4, lambda = 2.63))
# Same:
1 - ppois(4, lambda=2.63) # Cumulative distribution function / lower tail
# Same:
ppois(4, lambda=2.63, lower=FALSE) # upper tail
# EX 3
# This sounds like a geometric distribution
p <- 0.35
1 / p # Expected number of reports to read
#2.857143
# At most two
P <- p + (1 - p)*p
P
# At least three
1 - P
# 0.4225
# One solution
1 - (dgeom(0, p) + dgeom(1, p))
# Directly / R counts the number of failures
1 - pgeom(1,p) # we fail at most once
# Or even simpler way
pgeom(1,p, lower = F)
pgeom(1,p, lower = FALSE)
# EX 4
dpois(1, lambda = 2.3) * dpois(0, lambda = 0.7) # 1-0
dpois(2, lambda = 2.3) * dpois(0, lambda = 0.7) # 2-0
dpois(2, lambda = 2.3) * dpois(1, lambda = 0.7) # 2-1
# draw
dpois(0, lambda = 2.3) * dpois(0, lambda = 0.7) +
dpois(1, lambda = 2.3) * dpois(1, lambda = 0.7) +
dpois(2, lambda = 2.3) * dpois(2, lambda = 0.7) +
dpois(3, lambda = 2.3) * dpois(3, lambda = 0.7) +
dpois(4, lambda = 2.3) * dpois(4, lambda = 0.7) +
dpois(5, lambda = 2.3) * dpois(5, lambda = 0.7) +
dpois(6, lambda = 2.3) * dpois(6, lambda = 0.7) +
dpois(7, lambda = 2.3) * dpois(7, lambda = 0.7) +
dpois(8, lambda = 2.3) * dpois(8, lambda = 0.7) +
dpois(9, lambda = 2.3) * dpois(9, lambda = 0.7) +
dpois(10, lambda = 2.3) * dpois(10, lambda = 0.7)
# 0.1685989
# This is already very small
dpois(10, lambda = 2.3) * dpois(10, lambda = 0.7)
# Using for loop:
sum <- 0
for (k in 0:10)
{sum <- sum + dpois(k, lambda = 2.3) * dpois(k, lambda = 0.7)}
sum
#[1] 0.1685989
sum <- 0
for (k in 0:1000000) # loop until million
{sum <- sum + dpois(k, lambda = 2.3) * dpois(k, lambda = 0.7)}
sum
# [1] 0.1685989
# EX 5
# This looks like a binomial distribution
p = 0.6
n = 5
# All are alive
dbinom(5, size=5, prob=0.6)
# 0.07776
# At least three
dbinom(3, size=5, prob=0.6) +
dbinom(4, size=5, prob=0.6) +
dbinom(5, size=5, prob=0.6)
# 0.68256
# Cumulative version
1 - pbinom(2, 5, 0.6)
# OR
pbinom(2, 5, 0.6, lower = FALSE)
# Exactly two
dbinom(2, size=5, prob=0.6)
# 0.2304