2012-11-26 68 views
0

我有一個表員工(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 
+0

'1)'是什麼?這是你的功課嗎? –

+0

不,不在家工作 – Nyfer

+0

那麼那麼呢?這是您爲未來僱主考試的考試嗎?絕對看起來很粗略......問題的結構方式,幾乎肯定來自測試。我個人不喜歡幫助別人作弊。 –

回答

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

     from test.employee group by days 
+1

這將不會做他在問什麼... –

+0

我想最少計數,而不是最小編號 – Nyfer

1

這應該給你,在其上僱用的員工數量最少的工作日:

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

fyi,並非所有的數據庫都支持'group by alias',但都支持'2組' – Bohemian

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) 

這應該工作

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 
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