选择ID为null的第一列名称

时间:2014-12-09 09:12:11

标签: mysql sql sql-server-2008 select

我想按ID选择第一个空值列名称

我试过了:

SELECT Snap1,Snap2,Snap3,Snap4
where NULL
FROM tbtProgressSnap
where Id=3

Id | Snap1 | Snap2 | Snap3 | Snap4|
-----------------------------------
1  |       |       |/a.png |/b.png|
-----------------------------------
2  | d.png | m.png |       |      |
-----------------------------------
3  | g.png |l.png  |p.png  |      |

我希望得到相应的Id s

1 Snap1
2 Snap3
3 Snap4

4 个答案:

答案 0 :(得分:2)

试试这个:

SELECT WorkId, 
      (CASE WHEN Snap1 IS NULL OR snap1 = '' THEN 'Snap1'
            WHEN Snap2 IS NULL OR snap2 = '' THEN 'Snap2'
            WHEN Snap3 IS NULL OR snap3 = '' THEN 'Snap3'
            WHEN Snap4 IS NULL OR snap4 = '' THEN 'Snap4'
            WHEN Snap5 IS NULL OR snap5 = '' THEN 'Snap5'
            ELSE ''
       END) AS snapValue
FROM tbtProgressSnap 
WHERE WorkId=4;

检查SQL FIDDLE DMEO

<强>输出

| WORKID | SNAPVALUE |
|--------|-----------|
|      4 |     Snap5 |

答案 1 :(得分:1)

你需要一个具有超过min()的组的案例:

SELECT
    min(id) id, 
    CASE
        WHEN Snap1 IS NULL THEN 'Snap1'
        WHEN Snap2 IS NULL THEN 'Snap2'
        WHEN Snap3 IS NULL THEN 'Snap3'
        WHEN Snap4 IS NULL THEN 'Snap4'
    END snap
FROM tbtProgressSnap 
WHERE Snap1 IS NULL OR Snap2 IS NULL OR Snap3 IS NULL OR Snap4 IS NULL 
GROUP BY 2

请参阅SQL Fiddle,并将样本数据生成所需的输出。

答案 2 :(得分:0)

我不知道是否有内置功能,但您可以随时执行此操作:

SELECT Id,
CASE
    WHEN Snap1 IS NULL THEN 'Snap1'
    WHEN Snap2 IS NULL THEN 'Snap2'
    WHEN Snap3 IS NULL THEN 'Snap3'
    WHEN Snap4 IS NULL THEN 'Snap4'
END AS FirstNullColumnName,
CASE
    WHEN Snap1 IS NULL THEN Snap1
    WHEN Snap2 IS NULL THEN Snap2
    WHEN Snap3 IS NULL THEN Snap3
    WHEN Snap4 IS NULL THEN Snap4
END AS FirstNullColumnValue
FROM tbtProgressSnap

答案 3 :(得分:-1)

SELECT Snap1,Snap2,Snap3,Snap4 from tbtProgressSnap where snap1 =""