0

您有一张表,您希望根据该表计算两个不同表中的项目数。在这个例子中,我使用了建筑物,男人和女人

DROP TABLE IF EXISTS building;
DROP TABLE IF EXISTS men;
DROP TABLE IF EXISTS women;
CREATE TABLE building(name VARCHAR(255));
CREATE TABLE men(building VARCHAR(255), name VARCHAR(255));
CREATE TABLE women(building VARCHAR(255), name VARCHAR(255));
INSERT INTO building VALUES('building1');
INSERT INTO building VALUES('building2');
INSERT INTO building VALUES('building3');
INSERT INTO men VALUES('building1', 'andy');
INSERT INTO men VALUES('building1', 'barry');
INSERT INTO men VALUES('building2', 'calvin');
INSERT INTO men VALUES(null, 'dwain');
INSERT INTO women VALUES('building1', 'alice');
INSERT INTO women VALUES('building1', 'betty');
INSERT INTO women VALUES(null, 'casandra');

select 
   r1.building_name, 
   r1.men,
   GROUP_CONCAT(women.name) as women,
   COUNT(women.name) +  r1.men_count as count
from 
   (select 
      building.name as building_name,
      GROUP_CONCAT(men.name) as men,
      COUNT(men.name) as men_count 
   from 
      building 
   left join 
      men on building.name=men.building
   GROUP BY building.name) as r1
left join 
   women on r1.building_name=women.building 
GROUP BY r1.building_name;

可能有别的方法吗?上述做法的问题是子查询中两个表的列是隐藏的,需要在外查询中重新声明。在两个单独的集合操作中执行此操作会产生不对称的情况。我们同样可以先加入女性,然后加入男性。

4

2 回答 2

1

在 SQL Server 中,我只需用两个左连接连接两个子查询 - 如果您正在寻找对称性:

SELECT *
FROM building
LEFT JOIN (SELECT building, etc. FROM men GROUP BY etc.) AS men_summary
    ON building.name = men_summary.building_name
LEFT JOIN (SELECT building, etc. FROM women GROUP BY etc.) AS women_summary
    ON building.name = women_summary.building_name

我倾向于使用首先声明的公用表表达式而不是子查询——它更具可读性(但不是 ANSI——但两者都不是GROUP_CONCAT)。

于 2009-01-29T00:40:27.433 回答
1

使用 Union 合并 men/women 表中的数据

select building, [name] as menname, null as womenname from men
union
select building, null as menname, [name] as womenname from women

您现在在子查询中有一个单独的“表”,您可以加入、计数或其他任何东西。

顺便说一句,我可以理解为什么 Cas[s]andra 在没有人相信她的情况下被冷落,但是 dwain 呢,他是否同样被众神诅咒?

于 2009-01-29T01:05:17.303 回答