简体   繁体   中英

SQL Select Max of Columns Where Date is Not Null

I currently am using this query to select some data: SELECT DISTINCT a.code AS code, name, max(scen.Is3D) AS Is3D FROM locations LEFT JOIN ... . The scen table has columns Is3D and Date . I only want to select the max of items where the date IS NOT NULL . I tried max(scen.Is3D WHERE scen.Date IS NOT NULL) , but that didn't work. I cannot change anything after the FROM in my query, so I need that filtering to be done in the MAX, if possible. I am using MySQL 5.7.

You can use:

MAX(CASE WHEN scen.date IS NOT NULL THEN scen.Is3D END) AS Is3D

The CASE expression returns NULL when none of the WHEN conditions is met, but MAX() ignores null values, so this will just return the max of the Is3D columns in the selected rows.

So if we can't change anything after the FROM , then we cannot get a perfect solution here. Since you are SELECT ing out the NULL values. One thing that we can try if we can only modify the final output is this.

SELECT MAX(ISNULL(scen.Date,0))...

This will replace all the NULL s with 0, but it would help to know exactly what you are trying to do. Why are you so convinced that the query itself cannot be modified in any way?

The other solution would be to put the whole query in another wrapper.

That would look like:

SELECT * 
FROM ( 
[your whole query here]
) AS inner
WHERE inner.Date IS NOT NULL 

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