简体   繁体   English

SQL:按两个不同的查询分组

[英]SQL: Group by with two different queries

My table looks like that: 我的桌子看起来像这样:

id    sex    mailsent_number    click    click_time
1466  female       1             1       2017-08-14 10:01:28   
1467  female       1             1       2017-08-14 10:45:28
1468  female       1             NULL
1469  male         1             1       2017-08-14 10:11:28
1470  male         1             NULL
1471  male         0             NULL

The following query gets me basically what I want: 以下查询使我基本上得到了想要的东西:

select sex, 
count(mailsent_number) - count(click) NoClick, 
count(click) Click
from table group by sex;

A list with how many of each sex clicked and how many didn't click. 列出每个性别点击了多少,未点击多少的列表。 The ones who never got an email are not counted. 从未收到电子邮件的人将不会计入。

Now I would like to filter the clicks by click_time. 现在,我想按click_time过滤点击。 So I would like to know how many of each sex clicked BEFORE 2017-08-14 10:30 If I do this: 因此,我想知道在2017-08-14 10:30之前,每种性别点击了多少次:

select sex,
count(mailsent_number) - count(click) NoClick,
count(click) Click
from table where (click_time < '2017-08-14 10:30' or click_time is null) group by sex;

Then the amount of clicks is still correct, but the amount of "no clicks" is wrong, as the one who clicked after 10:30 is not counted at all, but should be counted as "no click". 那么点击量仍然是正确的,但是“没有点击”的数量是错误的,因为根本不算在10:30之后点击的人,而应该算作“没有点击”。

I don't know how I could get that result in one Query. 我不知道如何在一个查询中得到该结果。

I tried with subqueries to just find out how many people got the email in an individual query, but then the group by doesn't work anymore. 我尝试使用子查询来查找单个查询中有多少人收到了该电子邮件,但是group by不再起作用。

Any help on that would be very appreciated. 任何帮助,将不胜感激。

I assume the logic you want is a where clause: 我假设您想要的逻辑是where子句:

select sex, count(mailsent_number) - count(click) as NoClick,
       count(click) as Click
from table
where click_time < '2017-08-14 10:30' or click_time is null
group by sex ;

The reason your query seems to work is because MySQL treats sex and click_time < '2017-08-14 10:30' or click_time is null as a boolean expression, which evaluates to true or false. 您的查询似乎起作用的原因是因为MySQL将sex and click_time < '2017-08-14 10:30' or click_time is null为布尔表达式,其结果为true或false。 This then produces two rows, but there is not one for each value of sex . 这将产生两行,但对于sex每个值都没有一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM