Mysql按组

时间:2016-03-31 21:54:08

标签: mysql

我正在尝试提取每组的前1行。我是mysql的新手,不太确定如何限制

表clientcontracts

Client  Products    contract_date
A       pepsi       13/02/16
A       Cola        11/01/16
A       fanta       22/03/16
B       pepsi       15/01/16
B       Cola        18/01/16
B       fanta       12/03/16
c       pepsi       15/03/16
c       Cola        18/03/16
c       fanta       10/02/16

我做完了,

select Client,Products,contract_date 
from clientcontracts
group by Client,Products,contract_date
order by client,contract_date asc
limit 1

我在下面提供了实际和预期的输出。非常感谢

>     Actual output:
>     A Cola    11/01/16
>      
>     What i want:
>      
>      A    Cola    11/01/16
>      B    pepsi   15/01/16 
>      C    fanta   10/02/16

2 个答案:

答案 0 :(得分:1)

我假设您希望按客户分组最小日期?

SELECT Client, Products, contract_date 
FROM clientcontracts 
GROUP by Client 
ORDER BY Client, contract_date ASC

答案 1 :(得分:0)

给这个机会。它选择所有行,对其进行排序,将每个组的编号从1编号为n,并仅显示nr = 1的行。

  SELECT 
YEAR(att_date) AS y, 
MONTH(att_date) AS m, 
COUNT(distinct  att_date) as TOTAL_CLASSES,
count(distinct IF(remarks = '1' or remarks ='2' or remarks ='3', att_date, NULL)) as TOTAL_PRESENT FROM attendance WHERE class_id=11 AND student_id=15 GROUP BY y, m