简体   繁体   中英

mysql add condition for derived max function column

I have the following sql which is not working on the where condition.

SELECT t.PROJID,sum(t.UNITS) AS totalunits, sum(t.COST) AS totalcost, project, max(t.DATE) as lastupdated, PROJCODE 
FROM `projectcosts` `t` 
left join projects on projects.PROJID = t.PROJID 
where lastupdated LIKE '%2014-06-11%' 
GROUP BY t.PROJID

You should not use like on dates. The right solution is to simply truncate the date and do the comparison. However, you need to use the field in the data:

SELECT t.PROJID, sum(t.UNITS) AS totalunits,
       sum(t.COST) AS totalcost, project, max(t.DATE) as lastupdated, PROJCODE 
FROM `projectcosts` `t` left join
     projects on projects.PROJID = t.PROJID 
where date(t.date) = date('2014-06-11')
GROUP BY t.PROJID;

Or, if you have an index on lastupdated , using a range allows the use of the index:

SELECT t.PROJID, sum(t.UNITS) AS totalunits,
       sum(t.COST) AS totalcost, project, max(t.DATE) as lastupdated, PROJCODE 
FROM `projectcosts` `t` left join
     projects on projects.PROJID = t.PROJID 
where t.date >= date('2014-06-11') and t.date < date('2014-06-12')
GROUP BY t.PROJID;

You might really be wanting to use having , which is suggested by the use of the column alias instead of the base column. In that case:

SELECT t.PROJID, sum(t.UNITS) AS totalunits,
       sum(t.COST) AS totalcost, project, max(t.DATE) as lastupdated, PROJCODE 
FROM `projectcosts` `t` left join
     projects on projects.PROJID = t.PROJID 
GROUP BY t.PROJID
HAVING date(lastupdated) = date('2014-06-11');

Like can never be used with date field. If you are changing the type to vachar it is possible

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM