使用max of column,如果null,则使用min

时间:2016-01-06 17:37:49

标签: sql sql-server sql-server-2012

我在milestone列中有一个包含10个里程碑的表格。列milestone_achieved的值为OKNULLname列只有名称,每当有新人输入时,所有里程碑都会在NULL的数据库中输入。

以下是典型的表格:

+------+-----------+--------------------+
| name | milestone | milestone_achieved |
+------+-----------+--------------------+
| John |         1 | OK                 |
| John |         2 | OK                 |
| John |         3 | NULL               |
| John |         4 | NULL               |
| John |         5 | NULL               |
| John |         6 | NULL               |
| Mary |         1 | OK                 |
| Mary |         2 | OK                 |
| Mary |         3 | OK                 |
| Mary |         4 | OK                 |
| Mary |         5 | OK                 |
| Mary |         6 | OK                 |
| Tim  |         1 | NULL               |
| Tim  |         2 | NULL               |
| Tim  |         3 | NULL               |
| Tim  |         4 | NULL               |
| Tim  |         5 | NULL               |
| Tim  |         6 | NULL               |
+------+-----------+--------------------+

现在我希望SQL查询返回:

+------+-----------+--------------------+
| name | milestone | milestone_achieved |
+------+-----------+--------------------+
| John |         2 | OK                 |
| Mary |         6 | OK                 |
| Tim  |         1 | NULL               |
+------+-----------+--------------------+

我的查询现在看起来像这样:

SELECT name, MAX(milestone) FROM table HAVING milestone_achieved = 'OK' GROUP BY name
UNION ALL
SELECT name, MIN(milestone) FROM table HAVING milestone_achieved IS NULL AND MIN(milestone) = 1 GROUP BY name

这在90%的情况下起作用,例如在里程碑1和2已经完成,但是里程碑1是“未完成的”,因为它不符合特定标准或其他任何东西(想象一下装配汽车的装配线而且螺钉=milestone 1不够紧,但是油漆=milestone 2已经在它上面或者你能想象到的任何其他东西,我有可怕的想象力。)

我现在正在寻找一种正确显示这10%案例的方法。

1 个答案:

答案 0 :(得分:3)

一种方法是:

SELECT name, MAX(milestone)
FROM table
WHERE milestone_achieved = 'OK'
GROUP BY name
UNION ALL
SELECT name, MIN(milestone)
FROM table
GROUP BY name
HAVING MIN(milestone_achieved) IS NULL;

这遵循逻辑结构。您可以使用一个SELECT

执行此操作
SELECT name,
       COALESCE(MAX(CASE WHEN milestone_achieved = 'OK' THEN milestone END),
                MIN(milestone)
               )
FROM table
GROUP BY name