在WHERE中使用MIN

时间:2016-03-04 17:45:14

标签: mysql sql

有没有办法在MIN子句中使用WHERE

我试图将子查询插入到我的一个脚本中,而我设置的子查询最初是它自己的查询,它使用了这样的东西:

SELECT
   person, MIN(date)
FROM
   orders
WHERE
   date > "1/1/2015" and date < "1/31/2015"
GROUP BY
   person

这是为了确保FIRST记录,即最早的记录,是返回值。使用ORDER BY ASC LIMIT 1没有用。我想复制这个,以便我可以说:

WHERE
   otherPersons IN (
      SELECT
         person, MIN(date)
      FROM
         orders
      WHERE
         date > "1/1/2015" and date < "1/31/2015"
    )
      GROUP BY
        person

意思是,其他人必须是人,但只有那些最早日期在我日期之内的人才会传播。我理解这是不可能的,因为子查询只能选择1列。

我是SQL新手,对此问题的简单性感到抱歉。

3 个答案:

答案 0 :(得分:1)

You don't need only one

WHERE
   (otherPersons, date) IN (
      SELECT
         person, MIN(date)
      FROM
         orders
      WHERE
         date > "1/1/2015" and date < "1/31/2015"
      GROUP BY
        person
    )
      GROUP BY
        person

This is the same as a join with two clauses

JOIN  (
      SELECT
         person, MIN(date) as mindate
      FROM
         orders
      WHERE
         date > "1/1/2015" and date < "1/31/2015"
      GROUP BY
        person
    ) sub ON otherPersons = sub.person and date = sub.mindate

答案 1 :(得分:0)

try this code

SELECT
     person, MIN(date) as min_date -- field alias
  FROM
     orders
  WHERE         date > "1/1/2015" and date < "1/31/2015"
 HAVING Min(Date) > "xx/xx/xxxx"

you can field alias instead of MIN(DATE) in MySQL

答案 2 :(得分:0)

Your question is too ambiguous, so let me throw a couple sql and descriptions to see if one of these matches what you are looking for.

First, I am looking for all persons who had an order on the same minimum date within the time period in question

select 
      o.person,
      o.date
   from
      orders o
         JOIN ( select min(date) minDate
                   from orders
                   where date "1/1/2015" 
                     and date < "1/31/2015" ) dateOnly
            on o.date = dateOnly.minDate

Second, looking for ALL persons who placed an order within the time period in question AND want their OWN minimum order date. Person "A" could buy on Jan 1, but Person "B" buys on Jan 12, Person "C" on Jan 14. You would want all people with their date.

select 
      o.person,
      o.date
   from
      orders o
         JOIN ( select person, min(date) minDate
                   from orders
                   where date "1/1/2015" 
                     and date < "1/31/2015" 
                   group by person ) personDate
            on o.person = personDate.person
            AND o.date = personDate.minDate