【问题标题】:select company 2's value if exists, company 1's value if not如果存在则选择公司 2 的值,如果不存在则选择公司 1 的值
【发布时间】:2016-09-14 17:04:13
【问题描述】:

Windows Server 2012、MS SQL Server

我知道有一种基于集合的方法可以做到这一点,但我不知道如何简洁地表达我的问题以获得有用的谷歌答案。

tbl配置

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 并认为我可以让它工作,但它让我无法理解。我只是得到了表中所有值的列表。

【问题讨论】:

    标签: sql-server join set


    【解决方案1】:

    您正在寻找优先级查询。在 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 byrow_number() 子句中。

    【讨论】:

      【解决方案2】:
      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多