如何计算mysql中的子查询

gg58donl  于 2021-06-21  发布在  Mysql
关注(0)|答案(4)|浏览(339)

我有个问题:

Select
  DATE_FORMAT(calls.call_datetime, "%Y-%m-%d") as `groupdate`
from
  calls
WHERE calls.job_id =1
group by DATE_FORMAT(calls.call_datetime,
"%Y-%m-%d")

有回报:
分组日期
2018-07-06
2018-07-06
有两排。如何对上述查询进行计数,使结果变为一行的“2”?
我想要的是:
结果
2
谢谢,请帮帮我

2admgd59

2admgd591#

您应该使用count()

Select DATE_FORMAT(calls.call_datetime, "%Y-%m-%d") as groupdate , count(*)
from calls 
WHERE calls.job_id =1 
group by DATE_FORMAT(calls.call_datetime, "%Y-%m-%d")
nue99wik

nue99wik2#

这个问题模棱两可。因为一个日期有两行,所以期望的答案是“2”吗?如果不止一次约会呢?

SELECT COUNT(*) FROM calls WHERE ...; -- delivers "2"

SELECT COUNT(*) FROM calls WHERE ...; GROUP BY DATE(datetime) -- also delivers "2"

SELECT COUNT(DISTINCT DATE(call_datetime)) FROM calls WHERE ...; -- delivers "1"
t40tm48m

t40tm48m3#

最简单的方法是使用

Select
  COUNT(*) as Result
from
  calls
WHERE calls.job_id =1
group by DATE_FORMAT(calls.call_datetime, "%Y-%m-%d")

或者是一个传递表的方法

SELECT
 COUNT(*) as Result
FROM (
  Select
    DATE_FORMAT(calls.call_datetime, "%Y-%m-%d") as `groupdate`
  from
    calls
  WHERE calls.job_id =1 
  group by DATE_FORMAT(calls.call_datetime, "%Y-%m-%d")
) AS a

两个查询都应返回所需的相同预期结果。

btqmn9zl

btqmn9zl4#

尝试:

Select
  Count(DATE_FORMAT(calls.call_datetime, "%Y-%m-%d")) as `groupdate`
from
  calls
WHERE calls.job_id =1
group by DATE_FORMAT(calls.call_datetime,
"%Y-%m-%d")

相关问题