gpt4 book ai didi

Mysql 使用不同的参数多次使用同一列构建查询。使用子查询?

转载 作者:行者123 更新时间:2023-11-29 13:06:14 26 4
gpt4 key购买 nike

我有以下查询,它返回特定主题的约会次数:

select s.last_name, count(c.length)
from data.appointments a, data.subjects s, data.clinics c, research.sublog t
where s.id = a.subject_id and c.id = a.clinic_id and
s.ssn = t.ssn and a.status = '1' and
a.appt_date between '2012-10-01' and '2013-09-30' and a.appt_time not like '%01'
group by t.id

我想在同一查询中获得多个时间段的计数(添加不同的年份或季度)。我相信我需要为此使用子查询,但我很难破译在每个子查询中放置哪些条件以及需要保留在子查询之外的条件(我在这方面几乎没有经验)。这是正确的还是有其他方法可以更好地返回这样的结果?预先感谢您提供的任何帮助!

最佳答案

首先,您需要正确的连接语法。其次,问题的解决方案是条件聚合函数。这是一个例子:

select s.last_name,
sum(a.appt_date between '2012-10-01' and '2013-09-30') as cnt_2012,
sum(a.appt_date between '2013-10-01' and '2014-09-30') as cnt_2013
from data.appointments a join
data.subjects s
on s.id = a.subject_id join
data.clinics c
on c.id = a.clinic_id join
research.sublog t
on s.ssn = t.ssn
where a.status = '1' and
a.appt_time not like '%01'
group by t.id;

我没有进行更改,但您可能应该有 group by s.last_name 因为 select 子句中有 last_name 。而且,appt_time 上的过滤器对我来说没有意义。您不应在日期/时间字段上使用 like

关于Mysql 使用不同的参数多次使用同一列构建查询。使用子查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22676121/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com