简体   繁体   中英

Counting in Oracle 11g

all day I am struggling with oracle exrcises and again I stuck. I need to select last names of boxers with their wins of each weight category.

So I have:

  • table "boxer" with columns: id, fname, lname, weight
  • table "fight" with two foreign keys from table boxer (id_boxer1 and id_boxer2) and with one column winner (if boxer1 won then winner will be number 1, if boxer2 won then winner will be number 2)
  • table "category_weight" with columns: id, min_weight, max_weight, name (of a category)

Example:

CREATE TABLE category_weight(
    id    INTEGER NOT NULL,
    min_weight          SMALLINT NOT NULL,
    max_weight          SMALLINT NOT NULL,
    name  VARCHAR2(20) NOT NULL
);

ALTER TABLE category_weight ADD CONSTRAINT category_weight_pk PRIMARY KEY ( id );

CREATE TABLE boxer(
    id  INTEGER NOT NULL,
    fname       VARCHAR2(20) NOT NULL,
    lname      VARCHAR2(20) NOT NULL,
    weight     INTEGER NOT NULL
);

ALTER TABLE boxer ADD CONSTRAINT boxer_pk PRIMARY KEY ( id );

CREATE TABLE fight(
    id       INTEGER NOT NULL,
    winner SMALLINT NOT NULL,
    id_category_weight  INTEGER NOT NULL,
    id_boxer1     INTEGER NOT NULL,
    id_boxer2     INTEGER NOT NULL
);

ALTER TABLE fight ADD CONSTRAINT fight_pk PRIMARY KEY ( id );

ALTER TABLE fight
    ADD CONSTRAINT boxer_fk FOREIGN KEY ( id_boxer1 )
        REFERENCES boxer ( id );

ALTER TABLE fight
    ADD CONSTRAINT boxer_fk2 FOREIGN KEY ( id_boxer2 )
        REFERENCES boxer ( id );

ALTER TABLE fight
    ADD CONSTRAINT categ_weight_fk FOREIGN KEY ( id_category_weight )
        REFERENCES category_weight ( id );

INSERT INTO boxer
VALUES ('1', 'Johnny','Johnny','60');
INSERT INTO boxer
VALUES ('2', 'Anthonny','Anthonny','54');
INSERT INTO boxer
VALUES ('3', 'Anonimm','Anonimm','59');
INSERT INTO boxer
VALUES ('4', 'John','Johnowski','71');

INSERT INTO category_weight
VALUES ('1', '1','70','category1');
INSERT INTO category_weight
VALUES ('2', '71','100','category2');

INSERT INTO fight
VALUES ('1','1','1','1','2');
INSERT INTO fight
VALUES ('2','2','1','3','1');

Boxer with ID "1" won two fights in category1, so the result should be:

Lname          Category       Wins
Johnny         category1      2

Here, try this:

SELECT b.lname, 
       cw.max_weight AS WEIGHT_CLASS,
       COUNT(CASE WHEN f.winner = b.id THEN 1 ELSE NULL END) AS WINS
FROM boxer b
INNER JOIN fight f ON b.id = f.id_boxer1 OR b.id = f.id_boxer2
INNER JOIN category_weight cw ON f.id_category_weight = cw.id
GROUP BY b.lname, cw.max_weight

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM