2016-09-14 170 views
0

Windows Server 2012中,MS SQL Server的選擇公司2的值,公司1的值,如果不

我知道有一個基於集合的方式來做到這一點,但我無法弄清楚如何簡潔的短語我問題得到一個有用的谷歌答案。

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 

我想選擇公司2的值(或3或4或N ...),加上公司1的值,其中2沒有一個(順序不物質),如:

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