这些是我正在使用的表格。
CREATE TABLE status ('rowid' INTEGER PRIMARY KEY,
statusId INTEGER,
userId INTEGER,
invocation DATETIME,
expiration DATETIME,
FOREIGN KEY(userId) REFERENCES users(userId)
FOREIGN KEY(statusId) REFERENCES status_available(statusId)
);
INSERT INTO "status" ("rowid","statusId","userId","invocation","expiration") VALUES ('2','7','1','2016-05-01','2016-07-10');
INSERT INTO "status" ("rowid","statusId","userId","invocation","expiration") VALUES ('720','7','1','2016-09-22','2016-12-31');
INSERT INTO "status" ("rowid","statusId","userId","invocation","expiration") VALUES ('727','7','1','2017-01-01','2017-01-31');
INSERT INTO "status" ("rowid","statusId","userId","invocation","expiration") VALUES ('973','7','1','2017-08-12',NULL);
INSERT INTO "status" ("rowid","statusId","userId","invocation","expiration") VALUES ('976','1','1','2006-06-05',NULL);
CREATE TABLE status_available (
statusId INTEGER PRIMARY KEY NOT NULL,
statusName TEXT NOT NULL,
statusOrder INTEGER,
statusClass TEXT,
statusAccrueTime BOOLEAN
);
INSERT INTO "status_available" ("statusId","statusName","statusOrder","statusClass","statusAccrueTime") VALUES ('1','Active',NULL,'active','1');
INSERT INTO "status_available" ("statusId","statusName","statusOrder","statusClass","statusAccrueTime") VALUES ('5','Deceased',NULL,'dead','0');
INSERT INTO "status_available" ("statusId","statusName","statusOrder","statusClass","statusAccrueTime") VALUES ('7','Employee',NULL,'employee','1');
INSERT INTO "status_available" ("statusId","statusName","statusOrder","statusClass","statusAccrueTime") VALUES ('9','Inactive',NULL,'inactive','0');
INSERT INTO "status_available" ("statusId","statusName","statusOrder","statusClass","statusAccrueTime") VALUES ('16','Terminated',NULL,'term','0');
CREATE TABLE profile (
'userId' INTEGER PRIMARY KEY NOT NULL,'nameFamily' TEXT,'nameGiven' TEXT,'picture' TEXT,'dateJoined' DATETIME DEFAULT CURRENT_DATE, 'dateOfBirth' DATETIME, 'numberBadge' INTEGER, 'accessLevel' INTEGER, 'bio' BLOB, 'theme' TEXT,
FOREIGN KEY(userId) REFERENCES users(userId)
);
INSERT INTO "profile" ("userId","nameFamily","nameGiven","picture","dateJoined","dateOfBirth","numberSocial","numberBadge","accessLevel","bio","theme") VALUES ('1','John','Doe','6b71b487774b3f881a52073774560e39c60cab52.png','2006-06-05','1988-12-16','29','255',NULL,'night');
status
表自然地连接到status_available
以生成完整的行信息。目前为了获得某人的服务长度,我会进行以下查询。
SELECT SUM((IFNULL(expiration, date()) - invocation)) AS LenOfSrv FROM status NATURAL JOIN status_available WHERE userId = ? AND statusAccrueTime = 1 GROUP BY userId;
我遇到的问题是,所有日期都是SUMed。这不管他们的日期范围(由{expiration
OR date()
) - invocation
计算,是否已在另一行中计算。所以我的问题是,如何从SUM中删除已在另一行中考虑的日期范围?
答案 0 :(得分:0)
您想要完成的事情并不完全清楚。你的查询也很奇怪:如果你只有一个UserId,你就不必按它分组。 如果您说的是您检索了多条记录但具有相同的服务长度信息,那么答案很简单:使用distinct。
SELECT SUM(DISTINCT (IFNULL(expiration, date()) - invocation)) AS LenOfSrv
FROM status
NATURAL JOIN status_available
WHERE userId = ?
AND statusAccrueTime = 1