如何在sql语句中执行逻辑

时间:2013-09-18 15:22:17

标签: mysql sql

这是我的第二个(我称之为noobish)sql问题,虽然我知道我应该提高我的sql知识,在这种情况下,我已经离开了一个开发人员的高度和干燥。

无论如何,这个问题。我正在使用mysql 5

我正在处理商店程序api。其中一个sp是返回表的所有行以及来自该表的其他一些计算结果。

Table: reports
ID|col_1|col_2|col_3|col_4|col_5
--------------------------------
 x| xxx | xxx | xxx | xxx | xxx 

我正在尝试计算完成索引(之前的开发人员没有为此添加列,时间不允许我重构)。

所以如果......

col_1 is not null
col_2 is not null
col_3 is null
...

舞台将是2

如果......

col_1 is not null
col_2 is null <<-- notice the empty field
col_3 is not null

舞台将为1,因为有一个空字段。

因此,舞台会递增,直到有一个空字段。

现在我知道我可以检索所有行并使用php处理这些信息,但我不想转向系统的设计。

如果有人能指出我正确的方向,我会很感激。

2 个答案:

答案 0 :(得分:5)

Select Case
        When col_1 Is Null Then 0
        When col_2 Is Null Then 1
        When col_3 Is Null Then 2
        When col_4 Is Null Then 3
        When col_5 Is Null Then 4
        Else 5
        End

答案 1 :(得分:1)

你可以通过总结比赛来做到这一点:

select ((col_1 is not null) +
        (col_1 is not null and col2 is not null) +
        (col_1 is not null and col2 is not null and col3 is not null) +
        (col_1 is not null and col2 is not null and col3 is not null and col4 is not null) +
        (col_1 is not null and col2 is not null and col3 is not null and col4 is not null and col5 is not null)
       ) as IndexOfCompletion
. . .
相关问题