2016-03-01 42 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