我正在尝试加入一个表并获得一个计数,但我不能在表中计算两次ID计数。
表格1:
ID animal
-- ------
1 dog
2 dog
3 cat
4 cat
5 dog
表2:
ID
--
2
2
3
5
5
我需要计算表2中每种动物的数量。我可以将它加入并将ID更改为动物类型,然后计算每种动物的数量。
问题是每个ID只能计算一次。所以预期的产量是。
dog:2
cat:1
我的输出是哪里
dog:4
cat:1
尝试如下
select t1.animal, count( distinct t2.ID)
from table1 t1 join table2 t2 on t1.ID=t2.ID
group by t1.animal
你可以尝试下面使用count distinct id
select b.animal,count(distinct a.id) from table2 a
inner join table1 b on a.id=b.id
group by b.animal
试试这个:
SELECT t1.animal AS "Animal", COUNT(DISTINCT t1.ID) AS "No. of Animals"
FROM TABLE2 t2, TABLE1 t1
WHERE t2.ID = t1.ID
GROUP BY t1.animal
您可以在此处尝试嵌套选择。
SELECT
t.animal,
COUNT(t.ID) AS Count
FROM
(SELECT DISTINCT a.animal, b.ID FROM table1 a INNER JOIN table2 b ON a.ID = b.ID)t
GROUP BY t.animal