SQL服务器,HAVING子句问题

时间:2012-11-13 05:54:07

标签: sql sql-server sql-server-2008

我必须为我的数据库编写一个查询。查询如下。

/*  Query 9 – Most Valuable Players 
    "Who has received at least 2 MVP awards?"
    Produce a query to display the full name and number of MVP awards of any players who have been awarded the MVP in at least 2 races.  
    Make sure that races where no MVP was awarded are not included in the results, and order your results by the number of MVP awards in descending order.  
    Using your race view in this query is recommended.
    Hint:  Use HAVING to limit the results to players with an MVP count of at least 2.

我已尝试使用此代码:

CREATE VIEW playerView1
AS 
   select 
       player.id, player.firstName + ' ' + player.surname AS 'Full Name', race.mvp
   from 
       player  
   JOIN 
       race ON player.team = race.team
GO

SELECT playerView1.[Full Name]
From playerView1
GROUP BY [Full Name]
HAVING (playerView1.mvp) >1

并尝试了

SELECT 
    player.firstName + ' ' + player.surname AS 'Full_name', raceView.mvp AS 'MVP Number', 
    raceView.mvp_name AS 'MVP Name'
FROM 
    raceView
JOIN 
    player ON raceView.mvp_name = player.firstName
WHERE 
    raceView.mvp > 1

没有运气。关于我哪里出错的任何想法?并可能修复?

我使用第一个查询遇到的错误之一是

  

Msg 8121,Level 16,State 1,Line 4
  列'playerView1.mvp'在HAVING子句中无效,因为它不包含在聚合函数或GROUP BY子句中。

下面是我的整个数据库脚本,其中包括创建,填充和查看之前能够执行查询导致我的问题。

IF DB_ID ('Assignment2') IS NOT NULL
    BEGIN 
    DROP DATABASE Assignment2;
    END


/* Now create new database*/
CREATE DATABASE Assignment2;
GO
/* Make system use new database */
USE Assignment2;


/* Begin Creating tables */
/** Create Course Table **/
PRINT 'Creating table course.';
CREATE TABLE course (
    id INT IDENTITY, -- [CourseID] [int] IDENTITY(1,1) NOT NULL,
    name VARCHAR(50), -- [CourseName] [varchar](50) NULL,
    passingScore NUMERIC(18,0), -- [PassingScore] [numeric](18, 0) NOT NULL,
 CONSTRAINT course_pk PRIMARY KEY (id),
 CONSTRAINT passingScore CHECK (passingScore BETWEEN 0 AND 100)
);

/** Create RaceType Table**/
PRINT 'Creating table Race Type.' 
CREATE TABLE raceType (
    id INT IDENTITY, -- [RaceTypeID] [int] IDENTITY(1,1) NOT NULL,
    name VARCHAR(25) NOT NULL, -- [RaceTypeName] [varchar](25) NOT NULL,
CONSTRAINT raceType_pk PRIMARY KEY (id),
CONSTRAINT raceType_unique UNIQUE (name)
);

/** Create 'Teams' Table */
PRINT ' Creating table called Teams'
CREATE TABLE team (
    id INT IDENTITY, -- [TeamID] [int] IDENTITY (1,1) NOT NULL,
    name VARCHAR(25) NOT NULL, -- [TeamName] [varchar] (25) NOT NULL,
    biography TEXT, -- [Biography] [text] NULL,
    hyperlink VARCHAR(max), -- [Hyperlink] [varchar] (max) NULL,
CONSTRAINT team_pk PRIMARY KEY (id),
CONSTRAINT team_unique UNIQUE (name) 
);

/** Create "Players" Table**/
PRINT ' Creating table called Players'
CREATE TABLE player (
    id INT IDENTITY, -- [PlayerID] [int] IDENTITY(1,1) NOT NULL,
    firstName VARCHAR(50) NOT NULL, -- [FirstName] [varchar](50) NOT NULL,
    surname VARCHAR(50) NOT NULL, -- [Surname] [varchar](50) NOT NULL,
    coach INT, -- fk1       [CoachID] [int] NULL,
    team INT, -- fk2        [TeamID] [int] NULL,
CONSTRAINT player_pk PRIMARY KEY (id),
CONSTRAINT player_fk1 FOREIGN KEY (team) REFERENCES team (id),
CONSTRAINT player_fk2 FOREIGN KEY (coach) REFERENCES player (id)
);

/** Create "Races" Table **/
PRINT ' Creating table called Races'
CREATE TABLE race (
    id INT IDENTITY, -- [RaceID] [int] IDENTITY(1,1) NOT NULL,
    dateOfRace DATETIME NOT NULL, -- [DateOfRace] [datetime] NOT NULL,
    raceType INT NOT NULL, -- [RaceTypeID] [int] NOT NULL,
    course INT NOT NULL, -- [CourseID] [int] NOT NULL,
    team INT NOT NULL, -- [TeamID] [int] NOT NULL,
    observer INT NOT NULL, -- [ObserverID] [int] NOT NULL,
    mvp INT NULL, -- [MvpPlayerID] [int] NULL,
    finalScore INT NOT NULL, -- [FinalScore] [int] NOT NULL,
    pointsPenalised INT NOT NULL, -- [PointsPenalised] [int] NOT NULL,
CONSTRAINT race_pk PRIMARY KEY (id),
CONSTRAINT race_fk1 FOREIGN KEY (raceType) REFERENCES raceType(id),
CONSTRAINT race_fk2 FOREIGN KEY (course) REFERENCES course(id),
CONSTRAINT race_fk3 FOREIGN KEY (team) REFERENCES team(id),
CONSTRAINT race_fk4 FOREIGN KEY (observer) REFERENCES player(id),
CONSTRAINT race_fk5 FOREIGN KEY (mvp) REFERENCES player(id)
);
GO
/** End*/

填充脚本

/** Begin Populating "Course" table*/
PRINT 'Populating Course Table'

INSERT INTO course (name,passingScore) 
VALUES ('Easy Course','80');
INSERT INTO course (name,passingScore)
VALUES ('Medium Course','70');
INSERT INTO course (name,passingScore)
VALUES ('Hard Course','60');

/** Begin Populating "RaceType" Table */
PRINT 'Populating RaceType Table '

INSERT INTO raceType (name)
VALUES ('Ranked')
INSERT INTO raceType (name)
VALUES ('Practise')

/** Begin Populating "Teams" Table */
PRINT ' Populating Teams Table'

INSERT INTO team (name) 
VALUES ('Team BMW');
INSERT INTO team (name)
VALUES ('Team Porsche');
INSERT INTO team (name) 
VALUES ('Team Mercedez');
INSERT INTO team (name) 
VALUES ('Team AMartin');
INSERT INTO team (name)
VALUES ('Team Audi');

INSERT INTO player (firstName, surname)
VALUES ('hoger','amedi');
INSERT INTO player (firstName, surname, coach, team)
VALUES (' Lloyd', 'Banks', 1, 1);
INSERT INTO player (firstName, surname)
VALUES ('Silav', 'Govand');
INSERT INTO player (firstName, surname, coach, team)
VALUES ('hell', 'razor', 2, 2);
INSERT INTO player (firstName, surname, coach, team)
VALUES ( 'Alden', 'Padilla', 3, 1);
INSERT INTO player (firstName, surname)
VALUES ( 'Sina', 'Parker');
INSERT INTO player (firstName, surname, coach, team)
VALUES ( 'Lyle', ' Burks', 4, 2);
INSERT INTO player (firstName, surname, coach, team)
VALUES ('Rhona', 'Anthony', 5, 3);
INSERT INTO player (firstName, surname, team)
VALUES ('Seelie', 'Harper', 5);
INSERT INTO player (firstName, surname, coach, team)
VALUES ('Harper', 'Leonards', 6, 4)
INSERT INTO player (firstName, surname, coach, team)
VALUES ('jack', 'Merril', 7, 5)

INSERT INTO race (dateOfRace,finalScore,pointsPenalised,raceType,course,team,observer,mvp)
VALUES ('2011-12-03 06:01:49','53','4','2','1','4','2','1');
INSERT INTO race (dateOfRace,finalScore,pointsPenalised,raceType,course,team,observer,mvp)
VALUES ('2011-11-25 09:31:26','73','5','2','2','1','3','2');
INSERT INTO race (dateOfRace,finalScore,pointsPenalised,raceType,course,team,observer,mvp)
VALUES ('2011-12-03 19:36:34','52','1','1','1','5','4','3');
INSERT INTO race (dateOfRace,finalScore,pointsPenalised,raceType,course,team,observer,mvp)
VALUES ('2011-12-10 20:07:11','51','4','2','3','2','5','2');
INSERT INTO race (dateOfRace,finalScore,pointsPenalised,raceType,course,team,observer,mvp) 
VALUES ('2011-11-15 19:19:33','83','5','2','1','3','6','1');
INSERT INTO race (dateOfRace,finalScore,pointsPenalised,raceType,course,team,observer)
VALUES ('2011-11-27 02:32:09','53','1','2','3','5','7');
INSERT INTO race (dateOfRace,finalScore,pointsPenalised,raceType,course,team,observer)
VALUES ('2011-11-24 10:31:53','51','3','1','1','4','8');
INSERT INTO race (dateOfRace,finalScore,pointsPenalised,raceType,course,team,observer)
VALUES ('2011-11-19 15:17:32','70','2','1','2','5','9');
INSERT INTO race (dateOfRace,finalScore,pointsPenalised,raceType,course,team,observer)
VALUES ('2011-12-08 18:00:51','59','2','1','3','1','10');
INSERT INTO race (dateOfRace,finalScore,pointsPenalised,raceType,course,team,observer)
VALUES ('2011-12-09 19:55:53','67','5','2','3','5','10');





Select * 
From player;

Select *
From team;

Select *
From raceType;

Select *
From course;

Select *
From race;

查看脚本

USE Assignment2;
GO
PRINT 'Creating Player View'
GO
CREATE VIEW playerView AS 
SELECT player.id, player.firstName + ' ' + player.surname AS 'Full name', player.team, team.name, player.coach, coach.firstName, coach.surname 
FROM player
LEFT OUTER JOIN team
    ON player.team = team.id
    LEFT OUTER JOIN player as coach
        ON player.coach = coach.id;



GO
/* 
   Create a view which shows the following details of all races:
        • All of the columns in the race table
        • The name of the race type, course and team involved in the race
        • The full name of the player observing the race and the full name of the MVP (if applicable)
        • A calculated column with an alias of “unpenalised_score”, which adds the points penalised to the final score

   Creating this view requires a select statement using multiple joins and concatenation of names.  
   Make sure that you use the appropriate type of join to ensure that races without MVPs are still included in the results.
*/

-- Write your Race View here
PRINT 'Creating Race View'
GO
CREATE VIEW raceView AS 
SELECT race.id, race.dateOfRace, race.raceType, raceType.name AS raceTypeName, race.course, course.name AS courseName, race.team, team.name AS teamName, race.observer, obs.firstName + ' ' + obs.surname AS observer_name, race.mvp, mvp.firstName + ' ' + mvp.surname AS mvp_name, race.pointsPenalised, race.finalScore + race.pointsPenalised AS unpenalised_score, race.finalScore
FROM race
INNER JOIN raceType
    ON race.raceType = raceType.id
    INNER JOIN course
        ON race.course = course.id
        INNER JOIN team
            ON race.team = team.id
            LEFT OUTER JOIN player AS mvp
                ON race.mvp = mvp.id
                LEFT OUTER JOIN player AS obs
                    ON race.observer = obs.id;
GO 

SELECT * 
FROM playerView

SELECT *
FROM raceView

1 个答案:

答案 0 :(得分:4)

<击>

<击>

您需要使用COUNT

select      player.id, 
            player.firstName + ' ' + player.surname AS [Full Name],
            COUNT(*)
from        player  JOIN race 
                ON player.team = race.team
GROUP BY    id, player.firstName + ' ' + player.surname
HAVING      COUNT(*) >= 2

<击>

更新1

SELECT MVP_NAME, COUNT(*) TotalMVP
FROM   raceView
WHERE MVP IS NOT NULL
GROUP BY MVP_NAME
HAVING COUNT(*) >= 2
ORDER BY TotalMVP DESC;