我正在尝试生成一个表,其中列出了所有区号,办公室代码组合以及具有该区号,办公室代码组合的订户数量。
CREATE TABLE lines
(
portid integer NOT NULL primary key,
areacode varchar(3), --subscriber area code
officecode varchar(3), --subscriber office code
stationcode varchar(4), --subscriber station code
state varchar(4) NOT NULL, --line state BUSY, IDLE
foreign key (portid) references facilities(portid) on delete cascade
);
CREATE TABLE subscribers
(
portid integer NOT NULL,
name varchar(30) NOT NULL,
address varchar(50),
primary key (portid, name),
foreign key (portid) references facilities(portid) on delete cascade
);
SELECT
AREACODE, OFFICECODE, COUNT(SUBSCRIBERS.PORTID = LINES.PORTID)
FROM
LINES
INNER JOIN
SUBSCRIBERS ON SUBSCRIBERS.PORTID = LINES.PORTID;
但这仅输出819 | 227 | 50。它输出的是订户总数,而不是每个区号和局号组合的订户数。我在做什么错了?
答案 0 :(得分:0)
您将希望使用以下内容:
SELECT LINES.AREACODE, LINES.OFFICECODE, COUNT(*) AS SUBS
FROM LINES INNER JOIN SUBSCRIBERS ON SUBSCRIBERS.PORTID=LINES.PORTID
GROUP BY LINES.AREACODE, LINES.OFFICECODE
没有GROUP BY
子句,查询将为联接的数据集中的每个记录输出一行。
要输出计数符合某些条件的记录,您可以添加一个HAVING
子句,例如:
SELECT LINES.AREACODE, LINES.OFFICECODE, COUNT(*) AS SUBS
FROM LINES INNER JOIN SUBSCRIBERS ON SUBSCRIBERS.PORTID=LINES.PORTID
GROUP BY LINES.AREACODE, LINES.OFFICECODE
HAVING COUNT(*) = 3
答案 1 :(得分:0)
一个分组或嵌套选择可以使您找到想要的东西,我想出了
SELECT areacode, officecode, lines.portid, count(*) from lines inner join
subscribers on subscribers.portid=lines.portid group by areacode, officecode;