学习Microsoft SQL Server 2008技术内幕:T-SQL语法基础--第4章

Posted easy5

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了学习Microsoft SQL Server 2008技术内幕:T-SQL语法基础--第4章相关的知识,希望对你有一定的参考价值。

第4章 子查询

4.2.1 Exist 谓语:

use TSQLFundamentals2008
select * 
from Sales.Customers as C
where c.country=N\'Spain\'

select * 
from Sales.Customers as C
where c.country=N\'Spain\' and exists(select * from Sales.Orders as O where o.custid=C.custid)

select * 
from Sales.Customers as C
where c.country=N\'Spain\' and not exists(select * from Sales.Orders as O where o.custid=C.custid)
View Code

 

 4.3.2 连续聚和

select OBJECT_ID(\'Sales.OrderTotalsByYear\')
if OBJECT_ID(\'Sales.OrderTotalsByYear\') is not null  drop view Sales.OrderTotalsByYear

go
create view Sales.OrderTotalsByYear with schemabinding 
as 
  select 
    YEAR(o.orderdate) as orderyear,
    SUM(od.qty) as qty  
  from 
  Sales.Orders as o
    join Sales.OrderDetails as od on o.orderid=od.orderid
  group by YEAR(o.orderdate)
go
View Code

 查询:

select O1.orderyear, o1.qty,
    (select  SUM(o2.qty) from 
      Sales.OrderTotalsByYear as o2
      where o2.orderyear <= o1.orderyear
    ) as runqty
from  Sales.OrderTotalsByYear as O1
order by o1.orderyear
View Code

4.3.3 行为不当的子查询

SELECT custid, companyname
FROM Sales.Customers AS C
WHERE custid NOT IN(SELECT O.custid
                    FROM Sales.Orders AS O);
View Code

返回:

custid   companyname
22        Customer DTDMN
57        Customer WVAXS

插入一条custid=NULL的记录:

INSERT INTO Sales.Orders
  (custid, empid, orderdate, requireddate, shippeddate, shipperid,
   freight, shipname, shipaddress, shipcity, shipregion,
   shippostalcode, shipcountry)
  VALUES(NULL, 1, \'20090212\', \'20090212\',
         \'20090212\', 1, 123.00, N\'abc\', N\'abc\', N\'abc\',
         N\'abc\', N\'abc\', N\'abc\');
View Code
SELECT custid, companyname
FROM Sales.Customers AS C
WHERE custid NOT IN(SELECT O.custid
                    FROM Sales.Orders AS O);
View Code

返回0行

原因:

      NOT(22=1 Or 22=2 Or 22=NULL)

      NOT(False or False Or UnKnown)

      NOT UnKnow

      Unknow

      查询条件过滤UnKnown

而:

SELECT custid, companyname
FROM Sales.Customers AS C
WHERE  not exists (SELECT *
                    FROM Sales.Orders AS O where C.custid=O.custid);
View Code

SELECT custid, companyname
FROM Sales.Customers AS C
WHERE custid NOT IN(SELECT O.custid
                    FROM Sales.Orders AS O where O.custid is NOT null);
View Code

 

返回:

custid   companyname
22        Customer DTDMN
57        Customer WVAXS

 

以上是关于学习Microsoft SQL Server 2008技术内幕:T-SQL语法基础--第4章的主要内容,如果未能解决你的问题,请参考以下文章

Microsoft.SQL.Server2012.Performance.Tuning.Cookbook学习笔记

学习Microsoft SQL Server 2008技术内幕:T-SQL语法基础--第4章

07002 [Microsoft][ODBC SQL Server Driver]COUNT 字段不正确或语法错误

客户端统计表 (Microsoft SQL Server Management Studio)

学习SQL Server从在Linux上安装开始

Microsoft SQL Server 2016,T-SQL:根据各个日期获取数据集的日期范围