选择公司2的价值(如果存在),公司1的价值(如果不存在)

时间:2016-09-14 17:04:13

标签: sql-server join set

Windows Server 2012,MS SQL Server

我知道有一种基于集合的方式来做到这一点,但我无法弄清楚如何简洁地说出我的问题以获得有用的谷歌答案。

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并认为我可以让它发挥作用,但它让我望而却步。我最终得到了表中所有值的列表。

2 个答案:

答案 0 :(得分: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;

优先级的逻辑在order by的{​​{1}}子句中。

答案 1 :(得分: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