选择最大值和相应的列


Selecting Max Value and Corresponding Columns

我试图从更新列中获取最大日期,但也从该表返回相应的全名,目前正在发生的事情是最新的更新。返回日期,但第一次更新。顾问目前也正在返回,我们需要正确的全名以确定最大日期。

SELECT customer.id, 
       customer.name, 
       customer.retainer_value, 
       customer.customer_type, 
       clientdetails.performance, 
       clientdetails.url, 
       members.fullname AS acc_manager, 
       u.maxdate, 
       u.fullname 
FROM   customer 
       LEFT JOIN clientdetails 
              ON clientdetails.id = customer.id 
       LEFT JOIN members 
              ON members.id = customer.consultant_name 
       LEFT JOIN (SELECT updates.clientid, 
                         members.fullname, 
                         Max(updates.`date`) AS MaxDate 
                  FROM   updates 
                         LEFT JOIN members 
                                ON members.id = updates.consultant 
                  GROUP  BY updates.clientid 
                  ORDER  BY updates.date DESC) u 
              ON customer.id = u.clientid 
WHERE  customer.switchedoff = 'N' 
       AND customer.companyid <> '3' 

我认为在您的情况下最简单的方法是使用substring_index()/group_concat()方法:

SELECT customer.id, 
       customer.name, 
       customer.retainer_value, 
       customer.customer_type, 
       clientdetails.performance, 
       clientdetails.url, 
       members.fullname AS acc_manager, 
       u.maxdate, 
       u.fullname 
FROM   customer 
       LEFT JOIN clientdetails 
              ON clientdetails.id = customer.id 
       LEFT JOIN members 
              ON members.id = customer.consultant_name 
       LEFT JOIN (SELECT updates.clientid, 
                         substring_index(group_concat(m.fullname order by u.date desc separator '|'), '|', 1) as full_name
                         Max(updates.`date`) AS MaxDate 
                  FROM   updates u
                         LEFT JOIN members m
                                ON m.id = u.consultant 
                  GROUP  BY u.clientid
                 ) u 
              ON customer.id = u.clientid 
WHERE  customer.switchedoff = 'N' 
       AND customer.companyid <> '3' ;