2016-03-01 41 views
1

以下为标准来选择行:SQL - SELECT行有条件

  • 对于相同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 

我知道重新应该是一个更好的逻辑。请帮忙。提前致谢。

+1

输入和最终输出 – mohan111

+0

只需添加输入的任何样本数据和期望的输出 – Ganesha

+0

我只是做两个查询一个UNION - 一个地方P2存在,一个在它不(并使用连接而不是你的子查询)。根据数据,它可能是最快的 –

回答

1

如果P1,P2是不实际的数据,更改ORDER BYCASE 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 
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') 
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