如何创建查询以联接三个表并在SQL中进行计算?

时间:2019-06-15 17:44:38

标签: sql postgresql

我才刚刚开始SQL学习,却不知道如何解决下一个问题。

因此,有三个表:

given tables

任务是:“获取每个拥有者的宠物类型数量” 编写查询以生成以下结果:

desired output

目前最好的结果:

SELECT owners.OWNER_NAME, COUNT(pets.OWNER_ID) AS pets 
FROM owners
JOIN pets ON owners.ID = pets.OWNER_ID
JOIN pet_type ON pets.TYPE = pet_type.ID 
GROUP BY owners.OWNER_NAME;

它返回第一列带有所有者名称,第二列带有特定所有者宠物的总数。

将感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您需要条件聚合:

SELECT 
  o.OWNER_NAME, 
  SUM(CASE WHEN t.name = 'CAT' THEN 1 ELSE 0 END) CAT, 
  SUM(CASE WHEN t.name = 'DOG' THEN 1 ELSE 0 END) DOG,
  SUM(CASE WHEN t.name = 'SNAKE' THEN 1 ELSE 0 END) SNAKE
FROM owners o
JOIN pets p ON o.ID = p.OWNER_ID
JOIN pet_type t ON p.TYPE = t.ID 
GROUP BY o.OWNER_NAME;

我使用name作为描述表pet_type中类型的列的名称。将其更改为该列的实际名称。

答案 1 :(得分:0)

检查此。要获取每个所有者的宠物类型数量,仅将Pets表与owners表联接即可。 Pet.Type的DISTINCT计数将提供所需的输出。

SELECT
owners.ID,
owners.OWNER_NAME, 
COUNT(DISTINCT pets.TYPE) AS Num_Pet_Type 
FROM owners
INNER JOIN pets ON owners.ID = pets.OWNER_ID
GROUP BY owners.ID,owners.OWNER_NAME;

如果您希望每种类型的宠物数量,请在脚本下方使用此-

SELECT
owners.ID,
owners.OWNER_NAME, 
pets.TYPE,
COUNT(*) AS Num_Of_Pet
FROM owners
INNER JOIN pets ON owners.ID = pets.OWNER_ID
GROUP BY owners.ID,owners.OWNER_NAME,pets.TYPE;