我有员工使用officecode表,我想用 max 和 min 员工显示officecode ONLY ,
这是表格
+----------------+------------+
| employeenumber | officecode |
+----------------+------------+
| 1002 | 1 |
| 1056 | 4 |
| 1076 | 1 |
| 1143 | 7 |
| 1165 | 1 |
| 1166 | 6 |
.... .
.... .
+----------------+------------+
这就是我想要:
+------------+----------+
| officecode | empCount |
+------------+----------+
| 1| 6|
| 7| 2|
+------------+----------+
这是我的方法:
首先我COUNT和GROUP他们
然后从中选择MAX并使用SELECT MIN UNION它
但 SELECT MIN返回错误的officecode
这是我的代码:
SELECT officecode, MAX(empcount) AS 'empcount'
FROM
(
SELECT officecode, count(*) AS 'empCount'
FROM employees
GROUP BY officecode
)
AS temp
UNION
SELECT officecode, MIN(empcount) AS 'empcount'
FROM
(
SELECT officecode, count(*) AS 'empCount'
FROM employees
GROUP BY officecode
)
AS temp2
AS tmp
必须在那里,除非它会返回错误
它返回了:
+------------+----------+
| officecode | empCount |
+------------+----------+
| 1| 6|
| 1| 2|
+------------+----------+
任何知道我错的人吗?
或者你有另一种方法因为我的方法看起来如此loooooong,thx
答案 0 :(得分:1)
(
SELECT officecode, count(*) AS empCount
FROM employees
GROUP BY officecode
ORDER BY empCount ASC
LIMIT 1
)
UNION ALL
(
SELECT officecode, count(*) AS empCount
FROM employees
GROUP BY officecode
ORDER BY empCount DESC
LIMIT 1
)
答案 1 :(得分:0)
简单试试这个
SELECT officecode,MAX(empcount),MIN(empcount) count(*) AS 'empCount' FROM employees GROUP BY officecode
答案 2 :(得分:0)
你需要这个:
SELECT *
FROM
((SELECT ACTION, COUNT(ACTION) FROM t1
GROUP BY ACTION
ORDER BY ACTION DESC
LIMIT 1)
UNION
(SELECT ACTION, COUNT(ACTION) FROM t1
GROUP BY ACTION
ORDER BY ACTION ASC
LIMIT 1))t
检查此sqlfiddle:http://sqlfiddle.com/#!2/7116b5/1
答案 3 :(得分:-1)
试试这个,
SELECT officecode, MAX( empCount ) AS 'empCount'
FROM
(
SELECT officecode, COUNT( * ) AS 'empCount'
FROM employees
GROUP BY officecode ORDER BY empCount DESC
)
AS temp
UNION
SELECT officecode, MIN( empCount ) AS 'empCount'
FROM
(
SELECT officecode, COUNT( * ) AS 'empCount'
FROM employees
GROUP BY officecode ORDER BY empCount ASC
)
AS temp2