没有行匹配时,从左表中选择最后一条记录

时间:2019-01-25 00:57:45

标签: sql sql-server sql-server-2012

我很难弄清楚这一点,我有2个表,我想如果两个表中的行均不匹配,则从左表的最后一行中选择数据。例如:-

表1:-

Id     Category
1       Fruits
2       Electronics

表2:-

Id   Item         CategoryId
1    Television       2
2    Camera           2
3    Apple            1
4    foo              3

预期输出:

Television      Electronics
Camera          Electronics
Apple           Fruits
foo             Electronics  #No Id match so last record from 1st table

如果我不做左联接,它会给我空值,所以想知道在case语句中是否应该再次向第一个表加载数据,例如:-

SELECT B.Item
     , CASE WHEN B.Id IS NULL (--Take max and select table2 again?)
       ELSE B.Category END
FROM Table2 A
LEFT JOIN
    Table1 B
         ON A.CategoryId= BId

3 个答案:

答案 0 :(得分:4)

另一种选择是与Coalesce()配合使用的CROSS Join

示例

Select A.Item 
      ,Category = coalesce(B.Category,C.Category)
 From  T2 A
 Left Join  T1 B on A.CategoryId= B.Id
 Cross Join (Select Top 1 * From T1 Order by ID desc) C

返回

Item        Category
Television  Electronics
Camera      Electronics
Apple       Fruits
foo         Electronics
  

编辑-请求的更新

Select A.FoodID
      ,A.BarID
       A.Item 
      ,Category = coalesce(B.Category,C.Category)
 From  @T2 A
 Left Join  @T1 B on A.CategoryId= B.Id
 Cross Apply (
              Select Top 1 Category 
               From  T1 
               Where FoodID = A.FoodID    -- Notice the WHERE
                and  BarID  = A.BarID
                Order by ID Desc
            ) C

答案 1 :(得分:1)

几乎,我看不出有什么理由喜欢它。

SELECT B.Item
     , CASE WHEN B.Id IS NULL THEN
         ( SELECT Category,
             FROM ( SELECT ROW_NUMBER() OVER ( PARTITION BY 1 ORDER BY id DESC) AS rn,
                           Category
                      FROM Table1
                  ) TMP
            WHERE rn = 1
         )                
       ELSE B.Category END
FROM Table2 A
LEFT JOIN
    Table1 B
         ON A.CategoryId= BId

答案 2 :(得分:1)

您只能使用一个apply来完成此操作:

select t1.*, t2.category
from table1 t1 outer apply
     (select top (1) t2.*
      from table2 t2
      order by (case when t2.categoryId = t.category then 1 else 2 end),
               id desc
     ) t2;