SQL返回每组的单行

时间:2013-07-12 18:44:24

标签: mysql sql

我需要编写一个返回每个组的单行或记录的查询。 例如,我有一个表'employee',其中包含列:

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

由于

5 个答案:

答案 0 :(得分:7)

您需要将聚合函数应用于GROUP BY:

select min(id) id, 
  min(name) name,
  type
from yourtable
group by type;

请参阅SQL Fiddle with Demo

如果您不关心每种类型返回的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;

请参阅Demo

答案 1 :(得分:2)

您可以在SQL请求中使用“group by”。

假设你有一张表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
使用此方法

注意,不会选择或确定返回的名称和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;

答案 2 :(得分:1)

你应该为每种类型选择一个特定的记录,然后再加入以获得其他字段: -

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选择从哪些行中获取这些字段的行是未定义的。

答案 3 :(得分:0)

你试过这个吗?

SELECT * FROM employee GROUP BY group;

答案 4 :(得分:-1)

Select * from Employee
Group by Type