问题
I have two tables.
Table 1:
+------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| ID | varchar(255)| NO | PRI | NULL | |
| Sex | int(20) | YES | | NULL | |
| Age | varchar(255)| YES | | NULL | |
+------------+-------------+------+-----+---------+-------+
Table 2:
+-----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| ID | varchar(255) | NO | PRI | NULL | |
| var1 | varchar(255) | YES | | NULL | |
| var2 | varchar(255) | YES | | NULL | |
+-----------+--------------+------+-----+---------+-------+
What I want to do, is, based on a condition of three of the variables, as for example:
- Sex = 1
- Age = 3 (groups)
- var1 = "Wisconsin"
count the number of ocurrences. That is, the number of persons with that conditions.
The main problem that I´m finding is that the second table has a different amount of samples for each individual. So the number of rows in table2 is far bigger than in number1.
To make it clear:
Table1
+------------+-------------+------+
| ID | Sex | Age |
+------------+-------------+------+
| 1 | 1 | 2 |
| 2 | 0 | 4 |
| 3 | 0 | 3 |
+------------+-------------+------+
Table 2
+------------+-------------+---------+
| ID | Var1 | Var2 |
+------------+-------------+---------+
| 1.1 | "Wisconsin" | var2_1 |
| 1.2 | "Wisconsin" | var2_2 |
| 1.3 | "Wisconsin" | var2_3 |
+------------+-------------+---------+
I guess that firstly it is needed a preselection of the individuals based on var 1 for table 2, and then, I can carry on with the query for the ocurrences, but so far I didn´t manage to find a way of doing that.
Any help would be appreciated it.
回答1:
If I follow you correctly, you can use exists
to filter on table2
:
select count(*) as cnt
from table1 t1
where t1.sex = 1 and t1.age = 3 and exists (
select 1
from table2 t2
where t2.id = t1.id and t2.var1 = 'Wisconsin'
)
This counts rows in the first table for which at least one row in the second table has Wisconsin. If, on the other hand, you want to ensure that all rows in the second table satisfy the condition, then an option is:
select count(*) as cnt
from table1 t1
inner join (
select id
from table2
group by id
having min(var1 <=> 'Wisconsin') = 1
) t2 on t2.id = t1.id
where t1.sex = 1 and t1.age = 3
回答2:
You can find distinct
person as follows:
select count(distinct t1.id) as cnt
from table1 t1 join table2 t2 on t2.id = t1.id
where t1.sex = 1 and t1.age = 3 and t2.var1 = 'Wisconsin';
来源:https://stackoverflow.com/questions/65264816/count-ocurrences-based-on-several-conditions-for-two-tables