Using DISTINCT in SQL

142 views Asked by At

In AdventureWorks2012 database, I have to use the Sales.SalesPerson, Sales.SalesOrderHeader, Sales.SalesOrderDeatil, and Production.Product tables listing all Distinct products that have ProductID and Name which are sold in Territory 5.

Below is my attempted answer.

SELECT DISTINCT
    sod.ProductID,
    p.Name 
FROM
    Sales.SalesPerson SP,
    Sales.SalesOrderHeader SOH,
    Sales.SalesOrderDetail SOD,
    Production.Product P 
WHERE
    SP.BusinessEntityID = soh.SalesOrderID AND
    soh.SalesOrderID = sod.SalesOrderID AND
    sod.SalesOrderID = p.ProductID

The query executed successfully, but 0 rows were affected. What am I doing wrong?

2

There are 2 answers

1
Konstantin On
sod.SalesOrderID = p.ProductID

i'm guessing this, orderid = productid? probably mistake, maybe you wanted

sod.ProductID = p.ProductID
2
onedaywhen On
SELECT DISTINCT
    SOD.ProductID,
    P.Name AS ProductName
FROM
    Sales.SalesPerson SP,
    Sales.SalesOrderHeader SOH,
    Sales.SalesOrderDetail SOD,
    Production.Product P 
WHERE
    SP.BusinessEntityID = SOH.BusinessEntityID AND
    SOH.SalesOrderID = SOD.SalesOrderID AND
    SOD.ProductID = P.ProductID AND
    SOH.TerritoryID = 5;