我需要编写一个查询,每组返回一行或记录。例如,我有一个包含列的表“员工”:
id, name, type
1, John, full-time
2, Mike, full-time
3, Alex, part-time
4, Jerry, part-time
我需要返回类似的东西
1, John, full-time
4, Alex, part-time
谢谢
您将需要使用 GROUP BY 应用聚合函数:
select min(id) id,
min(name) name,
type
from yourtable
group by type;
如果您不关心每种类型返回什么 id/name,则上述方法有效。如果你这样做,那么你可以使用:
select t1.id,
t1.name,
t1.type
from yourtable t1
inner join
(
select min(id) id, type
from yourtable
group by type
) t2
on t1.id = t2.id
and t1.type = t2.type
或者
select t1.id,
t1.name,
t1.type
from yourtable t1
inner join
(
select min(name) name, type
from yourtable
group by type
) t2
on t1.name = t2.name
and t1.type = t2.type;
看演示
您可以在 SQL 请求中使用“分组依据”。
假设您有一张表 EMPLOYEES :
ID | NAME | TYPE
1 | 'John' | 'full-time'
2 | 'Mike' | 'full-time'
3 | 'Alex' | 'part-time'
4 | 'Jerry' | 'part-time'
你可以运行:
Select * from employees group by type
这将返回:
ID | NAME | TYPE
1 | John | full-time
3 | Alex | part-time
请注意,使用此方法返回的 Name 和 Id 不是选择的或确定的。要在返回的结果中包含特定的 Id(比如最大的),请首选以下内容:
SELECT *
FROM employees e
INNER JOIN
(
SELECT MAX(id) AS id, type
FROM employees
GROUP BY type
) e2
ON e.id = e2.id
AND e.type = e2.type;
您应该为每种类型选择一个特定的记录,然后返回以获取其余字段,如下所示:-
SELECT a.id, a.name, a.type
FROM employee a
INNER JOIN
(
SELECT type, MIN(id) AS id
FROM employee
GROUP BY type
) Sub1
ON a.id = Sub1.id
AND a.type = Sub1.type
虽然您可以执行以下操作
SELECT a.id, a.name, a.type
FROM employee a
GROUP BY type
这可能会产生副作用。id 和 name 来自的行可能不是该行(目前它们可能会),并且 MySQL 选择从哪一行获取这些字段是未定义的。
你试过这个吗?
SELECT * FROM employee GROUP BY group;
Select * from Employee
Group by Type