alexarcan

lab3_dbd(done)

Oct 16th, 2016
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. DROP table teams;
  2. DROP table results;
  3.  
  4. CREATE TABLE teams
  5. (
  6. team_id int primary key,
  7. team_name varchar2(20)
  8. );
  9.  
  10. CREATE TABLE results
  11. (
  12. team1_id int,
  13. team2_id int,
  14. CONSTRAINT fk_team1_id FOREIGN KEY(team1_id) REFERENCES teams(team_id),
  15. CONSTRAINT fk_team2_id FOREIGN KEY(team2_id) REFERENCES teams(team_id),
  16. goals_team1 int,
  17. goals_team2 int,
  18. Unique(team1_id, team2_id)
  19. );
  20.  
  21. insert into teams values(1,'Poli');
  22. insert into teams values(2,'MancesterUnited');
  23. insert into teams values(3,'FCBarselona');
  24.  
  25. insert into results values(1,2,5,0);
  26. insert into results values(2,1,4,1);
  27. insert into results values(2,3,0,0);
  28. insert into results values(3,2,1,0);
  29. insert into results values(3,1,0,3);
  30. insert into results values(1,3,1,1);
  31.  
  32.  
  33. --Create a View generating the Overall Team Ranking (Point Based)
  34. -- A team receives 3 points / match won
  35. -- A team receives 1 point for a draw
  36. -- Two teams can play each other two times (maximum) per season (one home game and one away)
  37.  
  38.  
  39. CREATE VIEW wonMatch_view(team_id) AS
  40. SELECT team1_id FROM results
  41. WHERE goals_team1 > goals_team2
  42. UNION ALL
  43. SELECT team2_id FROM results
  44. WHERE goals_team1 < goals_team2;
  45.  
  46.  
  47. CREATE VIEW drawMatch_view(team_id) AS
  48. SELECT team1_id FROM results
  49. WHERE goals_team1 = goals_team2
  50. UNION ALL
  51. SELECT team2_id FROM results
  52. WHERE goals_team1 = goals_team2;
  53.  
  54.  
  55. CREATE VIEW wonMatchPoints_view(team_id, team_points) AS
  56. SELECT t.team_id, (COUNT(m.team_id)*3) AS team_points
  57. FROM teams t, wonMatch_view m
  58. WHERE t.team_id = m.team_id
  59. GROUP BY t.team_id;
  60.  
  61.  
  62. CREATE VIEW drawMatchPoints_view(team_id, team_points) AS
  63. SELECT t.team_id, COUNT(d.team_id) AS team_points
  64. FROM teams t, drawMatch_view d
  65. WHERE t.team_id = d.team_id
  66. GROUP BY t.team_id;
  67.  
  68.  
  69. CREATE VIEW ranking_view (team_id, team_name, total_points) AS
  70. SELECT t.team_id, t.team_name, SUM(w.team_points + e.team_points) AS pts
  71. FROM teams t, wonMatchPoints_view w, drawMatchPoints_view e
  72. WHERE t.team_id=w.team_id AND t.team_id=e.team_id
  73. GROUP BY t.team_id, t.team_name
  74. ORDER BY pts DESC;
Add Comment
Please, Sign In to add comment