表結構與數據:https://github.com/XuePeng87/TSQLV4git
練習1
練習內容:編寫一個查詢,返回Orders表中能夠查到的活動最後一天的全部訂單 |
涉及的表:Sales.Orders |
輸出的列:orderid, orderdate, custid, empid |
正確結果:4行 |
SELECT orderid, orderdate, custid, empid
FROM Sales.Orders
WHERE orderdate = (
SELECT MAX(orderdate) FROM Sales.Orders
);
練習2
練習內容:編寫一個查詢,返回訂單數量最多的客戶的全部訂單。注意,在一個以上的客戶可能具備相同數量的訂單 |
涉及的表:Sales.Orders |
輸出的列:custid, orderid, orderdate, empid |
正確結果:31行 |
SELECT custid, orderid, orderdate, empid
FROM Sales.Orders
WHERE custid =
(
SELECT TOP 1 WITH TIES custid FROM Sales.Orders GROUP BY custid ORDER BY COUNT(*) DESC
);
練習3
練習內容:編寫一個查詢,返回在2016年5月1日或以後沒有下訂單的僱員 |
涉及的表:HR.Employees, Sales.Orders |
輸出的列:empid, firstname, lastname |
正確結果:4行 |
SELECT empid, firstname, lastname
FROM HR.Employees E
WHERE E.empid NOT IN (
SELECT O.empid FROM Sales.Orders AS O
WHERE O.orderdate >= '20160501'
);
練習4
練習內容:編寫一個查詢,返回有客戶可是沒有僱員的國家 |
涉及的表:Sales.Customers, HR.Employees |
輸出的列:country |
正確結果:19行 |
SELECT DISTINCT country FROM Sales.Customers
WHERE country NOT IN (
SELECT country FROM HR.Employees
);
練習5
練習內容:編寫一個查詢,返回每一個客戶活動最後一天的全部訂單 |
涉及的表:Sales.Orders |
輸出的列:custid, orderid, orderdate, empid |
正確結果:90行 |
SELECT O1.custid, O1.orderid, O1.orderdate, O1.empid
FROM Sales.Orders AS O1 WHERE O1.orderdate = (
SELECT MAX(O2.orderdate) FROM Sales.Orders AS O2
WHERE O2.custid = O1.custid
);
練習6
練習內容:編寫一個查詢,返回2015年下過訂單,可是2016年沒有下訂單的客戶 |
涉及的表:Sales.Customers, Sales.Orders |
輸出的列:custid, companyname |
正確結果:7行 |
SELECT custid, companyname FROM Sales.Customers AS C
WHERE EXISTS (
SELECT * FROM Sales.Orders AS O1
WHERE orderdate BETWEEN '20150101' AND '20151231' AND O1.custid = C.custid
) AND NOT EXISTS (
SELECT * FROM Sales.Orders AS O2
WHERE orderdate BETWEEN '20160101' AND '20161231' AND O2.custid = C.custid
);
練習7
練習內容:編寫一個查詢,返回訂購了產品12的客戶 |
涉及的表:Sales.Customers, Sales.Orders, Sale.OrderDetails |
輸出的列:custid, companyname |
正確結果:12行 |
SELECT custid, companyname
FROM Sales.Customers WHERE custid IN (
SELECT custid FROM Sales.Orders WHERE orderid IN (
SELECT orderid
FROM Sales.OrderDetails
WHERE productid = 12
)
);
練習8
練習內容:編寫一個查詢,計算每一個客戶及其月度的採購總量 |
涉及的表:Sales.CustOrders |
輸出的列:custid, ordermonth, qty |
正確結果:636行 |
SELECT custid, ordermonth, qty, (
SELECT SUM(qty) FROM Sales.CustOrders AS O2
WHERE O2.custid = O1.custid
AND O2.ordermonth <= O1.ordermonth
) AS runqty
FROM Sales.CustOrders AS O1;