多条件案例表达

时间:2019-03-08 08:01:23

标签: sql sql-server

OriData

+-----------------+-----------+-------+-------+------+
| selected_RowNum | V6_RowNum | SeqNo | Name  | IDNo |
+-----------------+-----------+-------+-------+------+
|               1 |         1 | A1234 | Yummy | 1234 |
|               1 |         2 | A1234 | Yummy | 1234 |
|               1 |         3 | A1234 | Yummy | 1234 |
|               1 |         4 | A1234 | Yummy | 1234 |
|               1 |         1 | B123  | Yummy | 1234 | << I want this
|               1 |         1 | C123  | Yummy | 1234 | << I want this
+-----------------+-----------+-------+-------+------+

我想要的结果

+-----------------+-----------+-------+-------+------+
| selected_RowNum | V6_RowNum | SeqNo | Name  | IDNo |
+-----------------+-----------+-------+-------+------+
|               1 |         1 | B123  | Yummy | 1234 |
|               1 |         1 | C123  | Yummy | 1234 |
+-----------------+-----------+-------+-------+------+

这是我的查询:

select 
case 
when selected_rownum=V6_RowNum and V6_RowNum=1 then 'updateonetime'
when selected_rownum=V6_RowNum and V6_RowNum>1 then 'updatemanytimes'
else '0'
end as NewColumnA, 
*
from Table #A

我内部连接V6和Selected表并进入#A

我想检查2个表之间的任何更新,所以我内部连接了两个表并为2个名为Selected_rowNum和v6_rownum(按日期排序)的表创建了rowNum。 Selected_RowNum = 1和V6_rowNum = 1(并且此V6_rownum不会针对相同的SeqNo,IDNo重复)

如果我更新1次,它将在V6表中触发。如果我多次更新,它将在SeqNo = A1234中多次触发V6表。如您所见,即使IDNo也在重复,但它可能会创建许多应用程序。因此,它需要基于IDNo和SeqNo以及Selected_RowNum = 1和V6_RowNum = 1的过滤器。

任何想法,如何获得我想要的结果?

2 个答案:

答案 0 :(得分:1)

从外观上,您只想显示没有更新条目的行的结果(仅V6_RowNum> 1?)。 为此,您需要检查表中是否不存在这些行,如下所示:

SELECT  CASE
        WHEN  selected_rownum=V6_RowNum and V6_RowNum=1 THEN 'updateonetime'
        WHEN  selected_rownum=V6_RowNum and V6_RowNum>1 THEN 'updatemanytimes'
        ELSE '0'
END as NewColumnA, 
*
FROM #A a
WHERE selected_RowNum = 1 
    AND V6_RowNum = 1
    AND NOT EXISTS
    (
        SELECT 1 FROM #A a2
        WHERE a2.SeqNo = a.SeqNo
            AND a2.V6_RowNum > 1
    )

答案 1 :(得分:0)

请尝试这个。

如果一次选择仅更新一次

Select selected_RowNum,seqNo,IDNo
    ,'updateonetime' As OneTime
    from @tbl 
    group by selected_RowNum,seqNo,IDNO
    having count(*) = 1

如果选择updateonlyone并多次更新时间,则

Select selected_RowNum,seqNo,IDNo
    ,CASE WHEN Count(*) > 1 THEN 'updatemanytimes' ELSE 'updateonetime' END
    from @tbl 
    group by selected_RowNum,seqNo,IDNO