SQL - 有条件地选择行

时间:2016-03-01 05:33:53

标签: sql-server tsql

以下是选择行的标准:

  • 对于相同的SysID,P2优先于P1。

我提出了这个逻辑

    DECLARE @Products table
    (
        Id int,
        SysId varchar(100)          
    );

    INSERT INTO @Products
    SELECT Id, SysId FROM ProductMain
    WHERE ProductCode = 'P2'

    INSERT INTO @Products
    SELECT Id, SysId FROM ProductMain WHERE ProductCode = 'P1'
    AND SysId NOT IN (SELECT SysId FROM @subscription)

    --Result
    SELECT Id,SysId FROM @Products

示例数据

Id  SysId  ProductCode
1   121    P1
2   121    P2
3   122    P1
4   123    P2
5   124    P1
6   124    P2

所需的输出

Id  SysId
2   121
3   122
4   123
6   124

我知道应该有一个更好的逻辑。请帮忙。提前谢谢。

3 个答案:

答案 0 :(得分:1)

如果P1,P2不是实际数据,请将ORDER BY更改为CASE WHEN ProductCode = 'P2' THEN 1 ELSE 2 END

SELECT *
FROM
(
   SELECT *, rn = row_number() over (partition by SysId ORDER BY ProductCode DESC)
   FROM   yourtable
) d
WHERE d.rn = 1

答案 1 :(得分:0)

你可以尝试这样的事情 -

select * from tableA as a
where exists(select 1 from tablea as b where b.sysid = a.sysid and b.productcode = 'P2')  or 
exists(select 1 from tablea as b where b.sysid = a.sysid and b.productcode <> 'P2') 

答案 2 :(得分:0)

考虑为ProductCodes分配的值如P1,P2,P3,并且您希望获得具有最高产品代码的Id。在你的情况下,P2是最高的。您可以使用以下给定的查询

SELECT *
FROM
(
    SELECT DENSE_RANK OVER(PARTITION BY SysId ORDER BY ProductCode DESC) As Rank
    FROM @Products
) AS ProductsNew
WHERE Rank = 1