如何正确使用SQL连接?

时间:2018-11-22 12:27:23

标签: sql sql-server tsql

我正在使用AdventureWorks数据库执行一些SQL练习。 我正在尝试将我的代码转换为使用Join语句,但似乎无法正确执行。

这是我最初用来显示客户名称,产品名称,销售金额以及购买数量和年份的代码:

SELECT FirstName, LastName, EnglishProductName, ProductAlternateKey, 
SUM(SalesAmount) as sales, sum(OrderQuantity) as Qty, CalendarYear 

FROM [AdventureWorksDW2017].[dbo].[FactInternetSales], 
     [AdventureWorksDW2017].[dbo].[DimProduct], 
     [AdventureWorksDW2017].[dbo].[DimCustomer], 
     [AdventureWorksDW2017].[dbo].[DimDate]

WHERE FirstName = 'Julia' And LastName = 'Wright' or 
      FirstName = 'Cedric' And LastName = 'Ma' or
      FirstName = 'David' and LastName = 'Rodriguez'

GROUP BY FirstName, LastName, EnglishProductName, ProductAlternateKey, CalendarYear
ORDER BY CalendarYear DESC, FirstName ASC, LastName

1 个答案:

答案 0 :(得分:0)

需要知道每个表中的哪些列相互关联。

(我们无法告诉您,因为我们看不到您数据库的设计。)

例如...

SELECT
    FirstName, LastName, EnglishProductName, ProductAlternateKey, 
    SUM(SalesAmount) as sales, sum(OrderQuantity) as Qty, CalendarYear 
FROM
    [AdventureWorksDW2017].[dbo].[FactInternetSales]
INNER JOIN
    [AdventureWorksDW2017].[dbo].[DimProduct]
        ON DimProduct.ProductID = FactInternetSale.ProductID
INNER JOIN
    [AdventureWorksDW2017].[dbo].[DimCustomer]
        ON DimCustomer.CustomerID = FactInternetSale.CustomerID
INNER JOIN
    [AdventureWorksDW2017].[dbo].[DimDate]
        ON DimDate.DateID = FactInternetSale.DateID
WHERE
    (FirstName = 'Julia'  AND LastName = 'Wright'   ) or 
    (FirstName = 'Cedric' AND LastName = 'Ma'       ) or
    (FirstName = 'David'  AND LastName = 'Rodriguez')
GROUP BY
    FirstName, LastName, EnglishProductName, ProductAlternateKey, CalendarYear
ORDER BY
    CalendarYear DESC, FirstName ASC, LastName

请注意将表名放在列名的前面。就像我在join子句中所做的一样。我可以推断FirstName来自DimCustomer,但是DimCustomer.FirstName使其明确而强大。