2016-09-14 4 views
0

のWindows Server 2012、MS SQL Serverの選択会社2の値が存在する場合、企業1の値でない場合

私はこれを行うにはセットベースの方法があります知っているが、私はどのように簡潔フレーズ私に把握することはできません有用なGoogleの回答を得るための質問。オーダーはしていません(

tblConfig

companyid var   val 
--------------------------------------------------------- 
1   fruit  orange 
1   game   Monopoly 
1   book   Joyland 
1   actor  Ernest Thesiger 
1   condiment ketchup 
2   fruit  apple 
2   book   Revival 
3   actor  Colin Clive 
3   condiment relish 
3   fruit  kiwi 
3   book   Tales From a Buick8 

は、私は(...または3、または4、またはN)会社2の値を選択したいと思い、プラス会社1の値がどこ2 1を持っていません問題)、のように:

2   fruit  apple 
1   game   Monopoly 
2   book   Revival 
1   actor  Ernest Thesiger 
1   condiment ketchup 

私はthis answerを見て、私はそれを動作させることができると思ったが、それは私を見逃さました。私はちょうどテーブルのすべての値のリストで終わる。

答えて

0

優先順位付けクエリを探しています。 SQL Serverでは、あなたはrow_number()を使用してこの操作を行うことができます。

select t.* 
from (select t.*, 
      row_number() over (partition by var 
           order by (case when companyid = 2 then 1 
               when companyid = 1 then 2 
              end) 
           ) as seqnum 
     from t 
    ) t 
where seqnum = 1; 

優先順位付けのためのロジックはrow_number()ためorder by句です。

0
Declare @YourTable table (companyid int,var varchar(50), val varchar(50)) 
Insert into @YourTable values 
(1,'fruit','orange'), 
(1,'game','Monopoly'), 
(1,'book','Joyland'), 
(1,'actor','Ernest Thesiger'), 
(1,'condiment','ketchup'), 
(2,'fruit','apple'), 
(2,'book','Revival'), 
(3,'actor','Colin Clive'), 
(3,'condiment','relish'), 
(3,'fruit','kiwi'), 
(3,'book','Tales From a Buick8') 

;with cteBase as (
    Select * 
      ,RowNr=Row_Number() over (Partition By var order by companyid Desc) 
    From @YourTable 
    Where companyid<=2 
) 
Select * from cteBase where RowNr=1 

戻り

companyid var   val    RowNr 
1   actor  Ernest Thesiger 1 
2   book  Revival   1 
1   condiment ketchup   1 
2   fruit  apple   1 
1   game  Monopoly  1 
関連する問題