当我从表中获得最大列时,必须得到相应的时间戳

时间:2015-12-15 14:17:40

标签: mysql

我需要从表中提取必要的字段以及相关的时间戳

SELECT * FROM Glm_Test.LicenseUsage where FeatureId='2';
Output :
VendorId,FeatureId,Total_Lic_Installed,Total_Lic_Used,Reserved,CurrentTime
1   2   106 19  67  2015-12-15 15:00:05
1   2   106 19  67  2015-12-15 15:02:02
1   2   106 19  69  2015-12-15 15:04:02
1   2   106 19  67  2015-12-15 15:06:01
1   2   106 20  67  2015-12-15 15:08:02
select VendorId,FeatureId,Total_Lic_Installed,Max(Total_Lic_Used),Reserved,CurrentTime from Glm_Test.LicenseUsage where FeatureId= '2' group by VendorId,FeatureId;
output:
1   2   106 20  69  2015-12-15 15:00:05

在上面的2个查询中 第一个查询列出表中的所有条目

我希望第二个查询返回列Total_Lic_Used的MAX值的时间戳,但不知怎的,它只返回第一个条目的时间戳。

非常感谢帮助。

1 个答案:

答案 0 :(得分:1)

count/max/min/sum...子句中选择不属于group by之类的聚合函数的列将会得到unexpected个结果:

其他RBBMS不会允许这些语句(给出错误):

  

sql server ==>选择列表,因为它不包含在任何一个中   聚合函数或GROUP BY子句

     

Oracle ==>不是GROUP BY表达式

您可以sub queryjoin

执行此操作
select 
    a.VendorId,
    a.FeatureId,
    a.Total_Lic_Installed,
    b.max_Total_Lic_Used,
    a.Reserved,
    a.CurrentTime 
from Glm_Test.LicenseUsage a 
join (
    select 
        VendorId,
        FeatureId,
        Max(Total_Lic_Used) max_Total_Lic_Used
    from Glm_Test.LicenseUsage 
    where FeatureId = '2' 
    group by VendorId, FeatureId
) b
on a.VendorId = b.VendorId and 
a.FeatureId = b.FeatureId and
a.Total_Lic_Used = b.max_Total_Lic_Used

imread

你也可以试试这个;

select 
    `VendorId`, 
    `FeatureId`, 
    `Total_Lic_Installed`, 
    `Total_Lic_Used`, 
    `Reserved`, 
    `CurrentTime`
from Glm_Test.LicenseUsage
order by Total_Lic_Used desc
limit 1

sql fiddle demo