如何根据sql server中行的列值从表中选择行

时间:2018-05-23 08:47:33

标签: sql sql-server tsql

我想根据sql server中的列值选择条件行,请查看下面带有所需结果的示例。

 WITH allData
AS (
select mlid=1,value=0,checkid=1
union all
select mlid=2,value=6,checkid=2
union all
select mlid=3,value=6,checkid=1
union all
select mlid=4,value=0,checkid=2
)
select * from allData 

结果

   Mlid  Value checked
    1    0      1
    2    6      2
    3    6      1
    4    0      2

要求的结果 - >
条件: - 如果检查的列值为1且值列为0,则显示选中的值值仅为2行 显示选中的列值1 如下结果

Mlid value checked   
2     6      2
3     6      1

1 个答案:

答案 0 :(得分:0)

这适用于您的样本数据,但几乎所有其他内容都会失败?

WITH allData AS (
    SELECT MLID = 1, [VALUE] = 0, CHECKID = 1
    UNION ALL
    SELECT MLID = 2, [VALUE] = 6, CHECKID = 2
    UNION ALL
    SELECT MLID = 3, [VALUE] = 6, CHECKID = 1
    UNION ALL
    SELECT MLID = 4, [VALUE] = 0, CHECKID = 2)
SELECT 
    CASE WHEN a1.CHECKID = 1 AND a1.VALUE = 0 THEN a2.MLID ELSE a1.MLID END AS MLID,
    CASE WHEN a1.CHECKID = 1 AND a1.VALUE = 0 THEN a2.[VALUE] ELSE a1.[VALUE] END AS [VALUE],
    CASE WHEN a1.CHECKID = 1 AND a1.VALUE = 0 THEN a2.CHECKID ELSE a1.CHECKID END AS CHECKID
FROM 
    allData a1
    INNER JOIN allData a2 ON a2.MLID = a1.MLID + 1 AND a2.CHECKID = 2
WHERE
    a1.CHECKID = 1;

我想这可能会让你开始更好的查询,甚至提出一些关于你真正需要的问题,以及这些行是如何相关的?