[英]All pairs with zero in sql
I have 2 tables: 我有2张桌子:
Pet_table
, which contains an ID number and type of pet (eg 'cat') Pet_table
,包含身份证号码和宠物类型(例如'猫') Size_table
, which contains an ID number and size ('S','M','L') Size_table
,包含ID号和大小('S','M','L') I want to print out how often the pairs occur, including zeros. 我想打印出对的频率,包括零。 For example:
例如:
id Pet_Type id SIZE
1 'cat' 1 'S'
2 'cat' 2 'S'
3 'cat' 3 'L'
4 'dog' 4 'M'
5 'snake' 5 'S'
6 'dog' 6 'M'
From this example, I'd want: 从这个例子中,我想要:
cat | S | 2
cat | M | 0
cat | L | 1
dog | S | 0
dog | M | 2
dog | L | 0
snake | S | 1
snake | M | 0
snake | L | 0
I almost have the answer, but I can't seem to get the zeros to print out. 我几乎有答案,但我似乎无法将零打印出来。
SELECT pet_type, size, COUNT(*) FROM pet_table LEFT JOIN size_table
ON pet_table.id=size_table.id GROUP BY pet_type,size;
Gives me: 给我:
cat | S | 2
cat | L | 1
dog | M | 2
snake | S | 1
I'm at my wits end, so any help would be appreciated. 我在我的智慧结束,所以任何帮助将不胜感激。 Doing this in sqlite3 if that matters.
如果重要的话,在sqlite3中执行此操作。
You need a driver table to get all possible combinations of pets and sizes and then use this for the joins: 您需要一个驱动程序表来获取宠物和大小的所有可能组合,然后将其用于连接:
SELECT pet_type, size, COUNT(st.id)
FROM (select distinct pet_type from pet_table) p cross join
(select distinct size from size_table) s LEFT JOIN
pet_table pt
on pt.pet_type = p.pet_type left join
size_table st
ON pt.id=st.id and st.size = s.size
GROUP BY p.pet_type, s.size;
Try this: 尝试这个:
select t1.pet_type, t1.size, ifnull(t2.[count], 0) [count]
from (
select distinct p.pet_type, t.size
from pet_table p
cross join (select distinct size from size_table) t) t1
left join (
SELECT p.pet_type, s.size, COUNT(*) [count]
FROM pet_table p
LEFT JOIN size_table s ON p.id=s.id
GROUP BY p.pet_type, s.size) t2 on t1.pet_type = t2.pet_type and t1.size = t2.size
order by t1.pet_type, t1.size
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.