使用子查询的分组计数的总和

时间:2019-05-14 20:04:16

标签: sql tsql adventureworks

使用Adventureworks数据库,我们被要求列出仅使用子查询而不使用JOINS的产品,其每次销售的数量大于15的供应商。

例如客户在SaleOrderID 43692中总共购买了34种产品,其中10种产品最初是从G&K购买的,而24种是从Integrated Sport购买的,因此Integrated Sport会在列表中列出

SELECT COLUMN_NAME FROM information_schema
WHERE TABLE_SCHEMA='database_name'
      AND TABLE_NAME = 'table_name'
      AND COLUMN_KEY = 'PRI';

我检查了是否可以创建此答案,但这只是部分正确,因为它使用了JOINS(在表之间放置a,仍被视为JOIN)

SalesOrderID | OrderQty | ProductID | BusinessEntityID | Name

43692 | 3 | 708 | 1520 | G & K Bicycle Corp.

43692 | 3 | 711 | 1520 | G & K Bicycle Corp.

43692 | 4 | 707 | 1520 | G & K Bicycle Corp.

43692 | 4 | 716 | 1636 | Integrated Sport Products

43692 | 4 | 714 | 1636 | Integrated Sport Products

43692 | 6 | 712 | 1636 | Integrated Sport Products

43692 | 10 | 715 | 1636 | Integrated Sport Products

哪个返回以下输出:

SELECT V.Name
FROM Purchasing.Vendor AS V
WHERE BusinessEntityID IN
    (SELECT BusinessEntityID
    FROM Sales.SalesOrderDetail AS S, Purchasing.ProductVendor AS P
    WHERE S.ProductID = P.ProductID
    GROUP BY S.SalesOrderID, P.BusinessEntityID
    HAVING SUM(S.OrderQty) > 15)
ORDER BY V.Name;

当我尝试将JOIN转换为子查询时,我无法使HAVING SUM正常工作,因为它假设SUM是各个单元中的,而不是销售订单中所有产品的总和。从供应商处购买

Chicago City Saddles

Crowley Sport

First Rate Bicycles

Fitness Association

G & K Bicycle Corp.

Green Lake Bike Company

Greenwood Athletic Company

Integrated Sport Products

International Trek Center

Jeff's Sporting Goods

Superior Bicycles

Team Athletic Co.

没有HAVING SUM节,内部部分按预期返回所有值。添加HAVING SUM()时,它只会返回购买数量大于15的产品,完全不考虑供应商。

我怀疑是因为它是按S.ProductID分组的,但是我无法删除它,否则会收到错误消息。是否有某种方法可以忽略它被分组的事实,而是根据我创建的BusienssEntityID对其进行分组?

0 个答案:

没有答案