简体   繁体   English

SQL选择日期不为空的最大列数

[英]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 ... . 我当前正在使用此查询来选择一些数据: SELECT DISTINCT a.code AS code, name, max(scen.Is3D) AS Is3D FROM locations LEFT JOIN ... The scen table has columns Is3D and Date . scen表中的列Is3DDate I only want to select the max of items where the date IS NOT NULL . 我只想选择日期IS NOT NULL的项目的最大值。 I tried max(scen.Is3D WHERE scen.Date IS NOT NULL) , but that didn't work. 我尝试了max(scen.Is3D WHERE scen.Date IS NOT NULL) ,但这没有用。 I cannot change anything after the FROM in my query, so I need that filtering to be done in the MAX, if possible. 我无法在查询中的FROM之后更改任何内容,因此,如果可能的话,我需要在MAX中进行过滤。 I am using MySQL 5.7. 我正在使用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. WHEN不满足任何WHEN条件时, CASE表达式将返回NULL ,但是MAX()忽略空值,因此这将仅返回所选行中Is3D列的最大值。

So if we can't change anything after the FROM , then we cannot get a perfect solution here. 因此,如果在FROM之后不能更改任何内容,则无法在此处获得理想的解决方案。 Since you are SELECT ing out the NULL values. 由于您正在SELECT NULL值。 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. 这会将所有NULL替换为0,但有助于准确了解您要执行的操作。 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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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