我正在使用Java和SQL,而我正试图计算宠物园里的所有山羊。我知道我可以使用以下查询:
SELECT COUNT(1) FROM PettingZoo pz WHERE pz.animalType = 'GOAT'
足够简单。现在,让我们说山羊有三种颜色:棕色,黑色或灰色。如果我想计算每种颜色的数量,我可以执行以下查询:
SELECT COUNT(1) FROM PettingZoo pz WHERE pz.animalType = 'GOAT' AND
pz.animalType.color = 'BROWN'
SELECT COUNT(1) FROM PettingZoo pz WHERE pz.animalType = 'GOAT' AND
pz.animalType.color = 'BLACK'
SELECT COUNT(1) FROM PettingZoo pz WHERE pz.animalType = 'GOAT' AND
pz.animalType.color = 'GREY'
此方法有效,但速度很慢。这样做会打开表四次:一次获得总计数,另外三次打开各个颜色。 有没有办法在一个查询中返回所有四种颜色?
编辑:为清楚起见,我们假设有15只山羊。九个是棕色,0个是黑色,6个是灰色。第一个查询将返回15.第二个查询将返回9.第三个和最后一个查询将分别返回0和6。我正在寻找一个一次返回所有四个值的东西(所以我不会在四个不同时间读同一个表)。可能是阵列? {15,9,0,6}
答案 0 :(得分:3)
SELECT SUM(case when pz.animalType.color = 'BROWN' then 1 else 0 end) as browns,
SUM(case when pz.animalType.color = 'BLACK' then 1 else 0 end) as blacks,
SUM(case when pz.animalType.color = 'GREY' then 1 else 0 end) as greys ,
COUNT(1) as total
FROM PettingZoo pz WHERE pz.animalType = 'GOAT' AND
(
pz.animalType.color = 'BROWN' or
pz.animalType.color = 'BLACK' or
pz.animalType.color = 'GREY'
)
WHERE pz.animalType is not null
答案 1 :(得分:1)
您可以使用group by获取一个查询中的所有计数:
SELECT
pz.animalType.color, COUNT(*)
FROM PettingZoo pz
WHERE pz.animalType = 'GOAT'
GROUP BY pz.animalType.color
答案 2 :(得分:1)
我认为Kevin忘记了组子句:
SELECT pz.animalType.color, COUNT(*) FROM PettingZoo pz WHERE
pz.animalType = 'GOAT' GROUP BY pz.animalType.color;