计数中的最小值

时间:2012-11-26 04:56:45

标签: mysql sql

我有一个表雇员(id,dept_id,salary,hire_date,job_id)。我必须执行以下查询。

显示在雇用最少员工的当天雇用的所有员工。

我已完成查询,但无法获得最少的查询。请检查一下是否正确。

          select id, WEEKDAY(hire_date)+1 as days,count(WEEKDAY(hire_date)+1) as count

           from test.employee  group by days

5 个答案:

答案 0 :(得分:1)

这可以让您获得雇用最少雇员的工作日:

SELECT 
   count(id) as `Total`,
   WEEKDAY(hire_date) as `DoW`
FROM
   test.employee
GROUP BY `DoW`
ORDER BY `Total` DESC LIMIT 1;

答案 1 :(得分:1)

select id from test.employee where hire_date in
    ( select count(id) count,hire_date 
      from test.employee
      order by count desc 
      limit 1)

这应该有效

答案 2 :(得分:1)

您可以尝试这样做,因为如果您有多个工作日雇员人数较少的工作日,则不会限制为一条记录。实际上它是有道理的。以下内容基于示例数据。

<强>查询:

-- find minimum id count
SELECT MIN(e.counts) INTO @min 
FROM (SELECT COUNT(*) as counts,
      WEEKDAY(hire_date+1) as day 
FROM employee
GROUP BY WEEKDAY(hire_date+1)) e
;

-- show weekdays with minimum id counts
SELECT e2.counts as mincount, 
WEEKDAY(e1.hire_date+1) as weekday
FROM employee e1
  JOIN (SELECT COUNT(id) as counts, 
        WEEKDAY(hire_date+1) as day
        FROM employee 
        GROUP BY day
        HAVING COUNT(*) = @min) e2
    ON WEEKDAY(e1.hire_date+1) = e2.day;

<强>结果:

MINCOUNT    WEEKDAY
1           6
1           3
1           4
1           2

答案 3 :(得分:0)

select min(id), WEEKDAY(hire_date)+1 as days,count(WEEKDAY(hire_date)+1) as count

       from test.employee  group by days

答案 4 :(得分:0)

       SELECT
           *
         FROM
       employee
       WHERE
          DAYOFWEEK(hire_date)
         IN 
      (
             SELECT 
            weekday 
        FROM
           (
             SELECT 
        count(*) as bcount, 
        DAYOFWEEK(hire_date) as weekday 
    FROM 
        employee as a
    GROUP BY 
        weekday
    HAVING
        bcount = (
            SELECT 
                MIN(tcount)
            FROM
                (
                    SELECT 
                        count(*) as tcount, 
                        DAYOFWEEK(hire_date) as weekday 
                    FROM 
                        employee 
                    GROUP BY 
                        weekday

                ) as t
        )
    ) as q