Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 按月份对事务进行分组的SQL查询_Mysql_Sql - Fatal编程技术网

Mysql 按月份对事务进行分组的SQL查询

Mysql 按月份对事务进行分组的SQL查询,mysql,sql,Mysql,Sql,我正在寻找一个SQL查询,它将返回在10月份(而不是11月份)有更多交易的客户的客户ID,或者只在11月份有交易的客户的ID(10月份没有)。月份列的类型为字符串(不是日期) 我想一个内部连接可以做到这一点,但过去我不知道如何处理这个问题 这就是我所尝试的 ---------------------------------------- |transaction_id|customer_id|month|value| ---------------------------------------

我正在寻找一个SQL查询,它将返回在10月份(而不是11月份)有更多交易的客户的客户ID,或者只在11月份有交易的客户的ID(10月份没有)。月份列的类型为字符串(不是日期)

我想一个内部连接可以做到这一点,但过去我不知道如何处理这个问题

这就是我所尝试的

----------------------------------------
|transaction_id|customer_id|month|value|
----------------------------------------

谢谢你清点记录。所以你要加总。您需要每个客户id的计数。因此您需要按客户id分组。您在查询中忘记了这一点

然后比较
HAVING
子句中的计数,即在计算完10月和11月记录之后

select customer_id
from tbl_name
where (select count(month is 'October') > count(month is 'November') from tbl_name)

您不需要访问表两次。只要汇总一下,看看你有什么:-)

你自己有没有尝试解决这个问题?显示代码。您的问题,并添加一些样本数据和基于该数据的预期输出。拜托,我已经试过了,但我知道这是错误的。我想使用一个子查询,检索每个客户id在10月份和11月份的计数,并进行比较,检查其中一个是否高于另一个。如果有SQL问题,您应该始终标记您的DBMS(MySQL或SQL Server或其他)。谢谢!,我怎样才能为11月份才买东西的客户打印客户id?我想这只会打印一个客户id,如果他们在10月有更多的话。你是对的,我忘了这一点。一种简单的方法是使用
添加标准。我已经更新了我的答案。嗯,我刚刚注意到我在('10月','11月')中添加了
where month
。因此,我们可以避免不必要的求值,也可以简化having子句。你是说在having块之前?从您的新编辑中,如果where语句为真(我们在两个月内都有购买),我们不是只会进入该块吗?我已经相应地更新了我的答案。是,
其中
位于
分组依据
具有
之前,即在聚合之前。
select customer_id
from tbl_name
where month in ('October', 'November')
group by customer_id
having count(case when month = 'October' then 1 end) >
       count(case when month = 'November' then 1 end)
    or count(case when month = 'October' then 1 end) = 0;