我正在使用汽车制造作为一个例子,很适合我的情况。
我现在的示例查询,它给出了每个州的简单计数:
SELECT state as State, count(distinct(idnumber)) as Total FROM database.table WHERE make IN('honda', 'toyota', 'subaru') GROUP BY state ORDER BY state
请注意,这将为我提供每辆汽车的计数,不包括福特,雪佛兰等等。制造清单将是每个品牌。
有没有办法可以打破这一点,以便在不诉诸子查询的情况下向我提供每个州的计数?在我的脑海中,它就像在计数中有一个where语句(distinct(idnumber))select,但我不确定是否可能。
这就是我的想法:
SELECT state as State, count(distinct(idnumber)) as Total_State, (count(distinct(idnumber)) WHERE make = 'honda') as Total_Honda WHERE make IN('honda', 'toyota', 'subaru') GROUP BY state ORDER BY state
答案 0 :(得分:4)
您可以通过以下方式向群组添加多个列:
GROUP BY
state, make
我可能会误解你的问题,但是你可以将两列分组,这样你就可以获得在CA中制作的ford数和在CA等中制作的hondas
要明确,您的查询将是:
SELECT
state as State,
count(distinct(idnumber)) as Total,
make as Make
FROM
database.table
WHERE
make IN('honda', 'toyota', 'subaru')
GROUP BY
state, make
ORDER BY
state
就像一个有趣的测试一样,我这样做了:
create table `cars` (
`id` int(11),
`make` varchar(255),
`state` varchar(255)
);
insert into cars(id, make, state) values
(1, 'honda', 'ca'), (2, 'honda', 'ca'), (3, 'toyota', 'ca'),
(4, 'toyota', 'az'), (5, 'toyota', 'az'), (6, 'honda', 'az');
SELECT state as State, count(id) as Total, make as Make
FROM cars
WHERE make IN('honda', 'toyota', 'subaru')
GROUP BY state, make
ORDER BY state
回来了:
+-------+-------+--------+
| State | Total | Make |
+-------+-------+--------+
| az | 1 | honda |
| az | 2 | toyota |
| ca | 2 | honda |
| ca | 1 | toyota |
+-------+-------+--------+
这是我的预期。那是你在想什么?