我对 ruby on rails 不熟悉,但这是你可以用 MySQL 做到这一点的方法。
样本数据:
CREATE TABLE Trips(
id int not null primary key,
organization_id int not null,
collaboration_organization_id int null
);
INSERT INTO Trips (id,organization_id,collaboration_organization_id)
VALUES
(1,1,5),
(2,1,1),
(3,1,2),
(4,11,1),
(5,1,null),
(6,2,null),
(7,10,null),
(8,6,2),
(9,1,3),
(10,1,4);
MySQL 查询:
SELECT organization_id,
sum(CASE WHEN collaboration_organization_id IS null THEN 1 ELSE 0.5 End) AS number
FROM Trips
GROUP BY organization_id;
通过以下方式试用:http ://www.sqlfiddle.com/#!2/1b01d/107
编辑:添加协作组织
样本数据:
CREATE TABLE Trips(
id int not null primary key,
organization_id int not null,
collaboration_organization_id int null
);
INSERT INTO Trips (id,organization_id,collaboration_organization_id)
VALUES
(1,1,5),
(2,1,1),
(3,1,2),
(4,11,1),
(5,1,null),
(6,2,null),
(7,10,null),
(8,6,2),
(9,1,3),
(10,1,4);
CREATE TABLE Organizations(
id int auto_increment primary key,
name varchar(30)
);
INSERT INTO Organizations (name)
VALUES
("Org1"),
("Org2"),
("Org3"),
("Org4"),
("Org5"),
("Org6"),
("Org7"),
("Org8"),
("Org9"),
("Org10"),
("Org11"),
("Org12"),
("Org13"),
("Org14"),
("Org15"),
("Org16");
MySQL查询:
SELECT O.id, O.name,
sum(CASE WHEN T.collaboration_organization_id IS null THEN 1 ELSE 0.5 End) AS number
FROM Organizations AS O LEFT JOIN Trips AS T
ON T.organization_id = O.id OR T.collaboration_organization_id = O.id
WHERE T.collaboration_organization_id = O.id OR O.id = T.organization_id
GROUP BY O.id;
http://www.sqlfiddle.com/#!2/ee557/15