在SQL Server中将行号添加为新列

时间:2016-04-04 08:13:55

标签: sql sql-server tsql window-functions

我需要第1,2,3,4,5行作为下面屏幕截图中的新列..

enter image description here

查询:

$query = "SELECT * FROM chat ORDER BY id DESC LIMIT 10";
$run = $con->query($query);
while($row = $run->fetch_array()):
    ?>
        <div id="chat_data">
            <table id="chattbl">
                <tr>
                    <td>
                        <h3><?php echo $row['name']; ?>:</h3>
                    </td>
                    <td>
                        <p><?php echo $row['msg']; ?></p>
                    </td>
                </tr>
            </table>
            <h5><?php echo formatDate($row['date']); ?></h5>
        </div>

请建议

2 个答案:

答案 0 :(得分:2)

不是简单的:

Select 
    ROW_NUMBER() OVER (ORDER BY CASE 
                                   WHEN VGID = 165 then 1    
                                   WHEN VGID = 158 then 2 
                                   WHEN VGID = 159 then 3 
                                   WHEN VGID = 157 then 4 
                                   WHEN VGID = 156 then 5 
                                END) AS RowNumber
    , * 
    from T_EMS_VGDM_RULEMST 
    where VGID in (156,157,158,159,165) 
    ORDER BY CASE 
     WHEN VGID = 165 then 1    
     WHEN VGID = 158 then 2 
     WHEN VGID = 159 then 3 
     WHEN VGID = 157 then 4 
     WHEN VGID = 156 then 5 
    END

答案 1 :(得分:1)

    Select 

ROW_NUMBER() OVER (ORDER BY vgid desc) AS RowNumber, 
 * from T_EMS_VGDM_RULEMST where VGID in (156,157,158,159,165) 
ORDER BY CASE 
 WHEN VGID = 165 then 1    
 WHEN VGID = 158 then 2 
 WHEN VGID = 159 then 3 
 WHEN VGID = 157 then 4 
 WHEN VGID = 156 then 5 
END