• sql-(Cross||Outer)Apply


    Apply - 涉及以下两个步骤中的一步或两步(取决于Apply的类型):
      1、A1:把右表表达式应用于左表的行
      2、A2:添加外部行
      Apply运算符把右表表达式应用于左输入的每一行。右表达式可以引用左输入中的列,对于左表中的每一行,都要计算一次右边输入的表达式。这一步会把左边的每一行和来自右表达式的响应行进行匹配,并将生成的结果集合合并起来,返回组合后的结果
      Cross Apply和Outer Apply总是包含步骤A1,只有Outer Apply才包含步骤A2
      如果内部(右)表表达式为外部(左)行返回的是空集,则Cross Apply不会返回该外部(左)行。而Outer Apply会返回这样的行,对于内表表达式的属性,则使用Null作为其占位符。

    If OBJECT_ID('Orders') Is Not Null Drop Table Orders;
    If OBJECT_ID('Customers') Is Not Null Drop Table Customers;
    Go
    
    Create Table Customers
    (
        CustomerID Char(5) Not Null Primary Key,
        City Varchar(10) Not Null
    );
    
    Create Table Orders
    (
        OrderID Int Not Null Primary Key,
        CustomerID Char(5) Null References Customers(CustomerID)
    );
    Go
    
    Insert Into Customers(CustomerID,City) Values('FISSA','Madrid');
    Insert Into Customers(CustomerID,City) Values('FRNDO','Madrid');
    Insert Into Customers(CustomerID,City) Values('KRLOS','Madrid');
    Insert Into Customers(CustomerID,City) Values('MRPHS','Zion');
    
    Insert Into Orders(OrderID,CustomerID) Values(1,'FRNDO');
    Insert Into Orders(OrderID,CustomerID) Values(2,'FRNDO');
    Insert Into Orders(OrderID,CustomerID) Values(3,'KRLOS');
    Insert Into Orders(OrderID,CustomerID) Values(4,'KRLOS');
    Insert Into Orders(OrderID,CustomerID) Values(5,'KRLOS');
    Insert Into Orders(OrderID,CustomerID) Values(6,'MRPHS');
    Insert Into Orders(OrderID,CustomerID) Values(7,Null);
    Select * From Customers

    Select * From Orders

    Select  a.CustomerID,a.City,c.OrderID From Customers a
    Cross Apply
    (
        Select Top 1 * From Orders b
        Where a.CustomerID=b.CustomerID
        Order By OrderID Desc
    ) c

    Select  a.CustomerID,a.City,c.OrderID From Customers a
    Cross Apply
    (
        Select Top 2 * From Orders b
        Where a.CustomerID=b.CustomerID
        Order By OrderID Desc
    ) c

    Select  a.CustomerID,a.City,c.OrderID From Customers a
    Outer Apply
    (
        Select Top 1 * From Orders b
        Where a.CustomerID=b.CustomerID
        Order By OrderID Desc
    ) c

  • 相关阅读:
    Windows 8.1 应用开发 – 触控操作
    Windows Phone App Studio 无码开发手机应用
    尝试HTML + JavaScript 编写Windows App
    Ubuntu远程连接MySQL(connection refused)解决方法
    [MySQL]查看用户权限与GRANT用法
    mysql 创建用户命令-grant
    搭建memcached使用:/usr/bin/phpize 安装memcached扩展的时候报错
    在linux中使用phpize安装php扩展模块
    跟锦数学全部资料
    33套2020数分高代试题参考解答[2020/04/14更新,更多请关注跟锦数学微信公众号]
  • 原文地址:https://www.cnblogs.com/zhyue93/p/sql_apply.html
Copyright © 2020-2023  润新知