MySQL:获得前1个ID

时间:2017-05-16 16:57:40

标签: mysql sql

我正在尝试弄清楚如何选择与客户ID关联的每个客户端ID的第一个属性ID。请帮忙。我该如何查询?

PropertyID  ClientID    CustomerID  Date
       10    1                 35    2004
       20    1                 35    2004
       30    2                 35    2004
       40    2                 35    2004
       50    3                 35    2004
       60    3                 35    2004
       70    4                 35    2004
       80    4                 35    2004
       90    5                 35    2004
      100    5                 35    2004
      110    6                 35    2005
      120    6                 35    2005
      130    7                 35    2005
      140    7                 35    2005
      150    8                 35    2005
      160    8                 35    2005
      170    9                 35    2005
      180    9                 35    2005
      220    15                37    2007
      240    15                37    2007
      260    16                37    2007
      270    16                37    2007  

预期结果:

PropertyID   ClientID   CustomerID
   10            1           35
   30            2           35
   50            3           35
   70            4           35
   90            5           35
   110           6           35
   130           7           35
   150           8           35 
   170           9           35
   220           15          37
   260           16          37     

2 个答案:

答案 0 :(得分:2)

SELECT MIN(PropertyID) AS PropertyID, ClientID, CustomerID
FROM table_name
GROUP BY ClientID,CustomerID;

http://sqlfiddle.com/#!9/e3dce/1

例如

答案 1 :(得分:2)

假设1st表示最低的propertyId,您可以在子查询中使用聚合来查找每个clientId的最低propertyId,然后将结果与原始表连接以获取其他相应的列。

select propertyId, clientId, customerId
from your_table t
join (
    select clientId,
        min(propertyId) as propertyId
    from your_table
    group by clientId
    ) t2 using (clientId, propertyId);

这假设propertyId是唯一的(至少每个客户端)。

Demo