T-SQL :联接查询练习 (杂)
Posted yuanzijian-ruiec
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了T-SQL :联接查询练习 (杂)相关的知识,希望对你有一定的参考价值。
1.每个客户返回一行订单 日期在~到~之间
SELECT E.empid, DATEADD(day, D.n - 1, ‘20090612‘) AS dt FROM HR.Employees AS E CROSS JOIN Nums AS D WHERE D.n <= DATEDIFF(day, ‘20090612‘, ‘20090616‘) + 1 ORDER BY empid, dt;
2.返回美国客户 并返回订单数量和总数量
SELECT C.custid, COUNT(DISTINCT O.orderid) AS numorders, SUM(OD.qty) AS totalqty FROM Sales.Customers AS C JOIN Sales.Orders AS O ON O.custid = C.custid JOIN Sales.OrderDetails AS OD ON OD.orderid = O.orderid WHERE C.country = N‘USA‘ GROUP BY C.custid;
3.返回 某个时间段 下单的用户以及订单 还要同时返回 在该时间段 没有下单的用户
SELECT C.custid, C.companyname, O.orderid, O.orderdate FROM Sales.Customers AS C LEFT OUTER JOIN Sales.Orders AS O ON O.custid = C.custid AND O.orderdate = ‘20070212‘;
4.返回某个时间段用户是否有订单
SELECT DISTINCT C.custid, C.companyname, CASE WHEN O.orderid IS NOT NULL THEN ‘Yes‘ ELSE ‘No‘ END AS [HasOrderOn20070212] FROM Sales.Customers AS C LEFT OUTER JOIN Sales.Orders AS O ON O.custid = C.custid AND O.orderdate = ‘20070212‘;
以上是关于T-SQL :联接查询练习 (杂)的主要内容,如果未能解决你的问题,请参考以下文章