-1

我是一名学生,花了足够的时间来完成这项工作。有人可以帮我解决这个问题:确定曾经售出的产品总数和从未售出的产品总数,就像在一个数据集中一样。

我猜 Union 、 Intersection 和 except 不适用于 Production.Product 和 sales.salesOrderDetail。

有人可以帮我吗

4

1 回答 1

0

If I have understood the question correctly then this should work

SELECT 
    SUM(CASE WHEN s.ProductId IS NULL THEN 1 ELSE 0 END) TotalProductsUnsold
    , SUM(CASE WHEN s.ProductId IS NULL THEN 0 ELSE 1 END) TotalProductsSold
FROM Production.Product p
LEFT JOIN (
    SELECT DISTINCT ProductId
    FROM Sales.SalesOrderDetail
) s ON s.ProductId = p.ProductId

Using union and except you could do something like

SELECT 
    'Total Products Unsold'
    , COUNT(ProductId) [Count]
FROM (
    SELECT
        ProductId
    FROM Production.Product 
    EXCEPT
    SELECT ProductId
    FROM Sales.SalesOrderDetail
) Products
UNION ALL
SELECT
    'Total Products Sold'
    , COUNT(DISTINCT ProductId) [Count]
FROM Sales.SalesOrderDetail

If you can't use / don't want to use COUNT(DISTINCT ...) then the second unioned select statement can be replaced with

SELECT 
    'Total Products Unsold'
    , COUNT(ProductId) [Count]
FROM (
    SELECT
        ProductId
    FROM Production.Product 
    INTERSECT
    SELECT ProductId
    FROM Sales.SalesOrderDetail
) Products
于 2013-03-29T10:34:03.140 回答