简体   繁体   English

在where子句中使用Select Min和MAx

[英]Use a Select Min and MAx in your where clause

I am using a number of select statements to drive results, however I have 2 select statements which returns the minimum time for appointment and max time for appointment. 我使用许多select语句来提高结果,但是我有2条select语句,它们返回最小约会时间和最大约会时间。 However where the min and max are the same, I want to remove from within my where clause. 但是,在最小和最大相同的地方,我想从where子句中删除。

SELECT
  APPOINTMENTS.userid,
  users.LOCATIONID,
  MIN(APPOINTMENTTIME) AS mintime,
  MAX(APPOINTMENTTIME) AS maxtime

FROM appointments
WHERE APPOINTMENTDATE BETWEEN '2017-01-07' AND '2017-01-07'
AND NOT mintime <> maxtime
GROUP BY appointments.USERID,
         users.LOCATIONID,
         appointments.APPOINTMENTDATE

I get the error Mintime is not valid. 我收到错误消息Mintime无效。

I am sure I need to hold this in a new sub select but not sure.. 我确定我需要将其保留在新的子选择中,但不确定。

Cheers 干杯

The HAVING clause is used for aggregate functions, eg HAVING子句用于聚合函数,例如

HAVING NOT MIN(APPOINTMENTTIME) <> MAX(APPOINTMENTTIME)

I don't know why you are using a double negative in your predicate though, based on your description you just need <> 我不知道您为什么在谓词中使用双重否定,根据您的描述,您只需要<>

HAVING MIN(APPOINTMENTTIME) <> MAX(APPOINTMENTTIME)

Try this as per Sql Server 按照Sql Server尝试一下

        SELECT * FROM (
        select   
        APPOINTMENTS.userid, 
        users.LOCATIONID,
        min(APPOINTMENTTIME) as mintime, 
        max(APPOINTMENTTIME) as maxtime
        from appointments
        where 
        APPOINTMENTDATE between '2017-01-07' and '2017-01-08'

        group by 
        appointments.USERID,users.LOCATIONID,
        appointments.APPOINTMENTDATE
        )as t WHERE  mintime <> maxtime

Please try 请试试

select   
APPOINTMENTS.userid, 
users.LOCATIONID,
min(APPOINTMENTTIME) as mintime, 
max(APPOINTMENTTIME) as maxtime

from appointments
where 
APPOINTMENTDATE between '2017-01-07' and '2017-01-07'

group by 
appointments.USERID,users.LOCATIONID,
appointments.APPOINTMENTDATE
having min(APPOINTMENTTIME)  <> max(APPOINTMENTTIME)

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

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