【问题标题】:Is there a way to get a query return the users that the count of a certain condition is above a certain number?有没有办法让查询返回某个条件的计数高于某个数字的用户?
【发布时间】:2021-01-11 06:31:07
【问题描述】:

我在尝试找出编写 SQL 查询的正确方法时遇到了麻烦。好的,假设我们有三个表 MyUser、Consult、Measurement。我想要一个查询,返回在过去 30 天内创建超过 30 次测量但在过去 30 天内未收到咨询的用户。到目前为止,我得到了这样的东西:

FROM MyUser a
where a.isActive = 1 AND a.email = 'test@gmail' AND a.userRole = 'patient'
having 30 < (select COUNT(*) From Measurement m, Consults c
        WHERE c.patient_email = 'test@gmail'
         AND m.patient_email = 'test@gmail'
         AND m.measurement_created_date BETWEEN '2020-07-20' AND '2020-10-20'
         AND NOT c.consult_created_date BETWEEN '2020-10-20'AND '2020-11-20')

这不能正常工作。 另一种方法是:

SELECT COUNT (*) FROM Measurement m, MyUser a, Consults c
WHERE a.isActive = 1 AND a.email = 'test@gmail.com' AND a.userRole = 'patient'
AND c.patient_email = 'test@gmail'
AND m.patient_email = a.email
AND m.measurement_created_date BETWEEN '2020-08-10'AND '2020-09-10'
AND NOT c.consult_created_date BETWEEN '2020-08-10'AND '2020-19-10'

或类似的东西,但这不返回用户,只返回计数。有人可以为此提供一些指导或解决方案吗?谢谢

【问题讨论】:

  • 为了获得正确的结果,您需要编写正确的查询。请研究如何正确使用GROUP BYHAVING
  • 这也是2020年。请学会正确使用JOIN。它已经存在超过 25 年了。
  • 请用您正在运行的数据库标记您的问题:mysql、oracle、sqlserver...?
  • 我看不出你的日期与“过去 30 天”有什么关系。
  • 查询是关于了解我如何能够返回希望的结果。电子邮件和日期仅用于测试目的,因为无论哪种方式,它都将被修改为通过 java hibernate 使用,如 ` "AND m.measurement_created_date BETWEEN :from AND :to " + "AND NOT(c.consult_created_date BETWEEN :from AND : to) " .setParameter("from", LocalDate.now().minusMonths(1)) .setParameter("to", LocalDate.now()) `

标签: sql sql-server count subquery where-clause


【解决方案1】:

向我返回在过去 30 天内创建超过 30 次测量但在过去 30 天内未收到咨询的用户的查询

您可以使用子查询来做到这一点。您的要求字面意思是:

select *
from myuser u
where 
    (   
        select count(*)
        from measurement m
        where m.patient_email = u.email
          and m.measurement_created_date between '2020-07-20' and '2020-10-20'
    ) > 30
    and not exists (
        select 1
        from consults c
        where c.patient_email = u.email
          and m.consult_created_date between '2020-07-20' and '2020-10-20'
    )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-19
    • 2015-07-19
    • 1970-01-01
    • 1970-01-01
    • 2011-11-26
    • 2022-01-21
    • 2019-08-14
    • 1970-01-01
    相关资源
    最近更新 更多