复杂的SQL计数查询

时间:2013-12-14 12:10:09

标签: sql hsqldb

您好我的任务中遇到了一个SQL查询,并希望得到一些帮助。

我需要获取最佳执行项目的项目ID - 项目(VERY_GOOD记录计数+ GOOD记录计数) - (VERY_BAD记录计数+ BAD记录计数)最大

我在数据库中的架构和测试记录(HSQLDB)

CREATE TABLE
    PROJECT
    (
        ID IDENTITY NOT NULL PRIMARY KEY,
        PROJECT_NAME VARCHAR(255) NOT NULL
    );

CREATE TABLE
    RECORD
    (
        ID IDENTITY NOT NULL PRIMARY KEY,
        RESULT VARCHAR(255) NOT NULL,
    );

CREATE TABLE
    RECORD_PROJECT
    (
        PROJECT_ID INTEGER NOT NULL,
        RECORD_ID INTEGER NOT NULL,
        PRIMARY KEY(PROJECT_ID, RECORD_ID),
        FOREIGN KEY (PROJECT_ID) REFERENCES PROJECT(ID) ON DELETE CASCADE,
        FOREIGN KEY (RECORD_ID) REFERENCES RECORD(ID)
    );  

测试数据:

INSERT INTO PROJECT (PROJECT_NAME) VALUES ('Bake a cake');
INSERT INTO PROJECT (PROJECT_NAME) VALUES ('Clean the house');

INSERT INTO RECORD (RESULT) VALUES ('GOOD');
INSERT INTO RECORD (RESULT) VALUES ('VERY_GOOD');
INSERT INTO RECORD (RESULT) VALUES ('VERY_GOOD');
INSERT INTO RECORD (RESULT) VALUES ('BAD');
INSERT INTO RECORD (RESULT) VALUES ('VERY_BAD');

INSERT INTO RECORD_PROJECT (PROJECT_ID, RECORD_ID) VALUES (0,0);
INSERT INTO RECORD_PROJECT (PROJECT_ID, RECORD_ID) VALUES (1,1);
INSERT INTO RECORD_PROJECT (PROJECT_ID, RECORD_ID) VALUES (1,2);
INSERT INTO RECORD_PROJECT (PROJECT_ID, RECORD_ID) VALUES (0,3);
INSERT INTO RECORD_PROJECT (PROJECT_ID, RECORD_ID) VALUES (1,4);

(我从表中删除了不相关的字段)

所以有了这些数据我有3个好的记录和2个坏的,我需要得到具有最高'评级'的项目,根据现在这个将是清理房子其他项目3个好评为2个负面。

也许有人会想到这一点,谢谢!

1 个答案:

答案 0 :(得分:0)

那应该是MySQL-Dialect中的(不是testet)SQL:

SELECT rp.PROJECT_ID, p.PROJECT_NAME
   SUM(CASE WHEN rp.RECORD_ID < 3 THEN 1 ELSE 0 END) AS rating
FROM RECORD_PROJEKT AS rp
JOIN PROJECT AS p ON p.ID = rp.PROJECT_ID
GROUP BY rp.PROJECT_ID
ORDER BY rating DESC