重复数据问题SQL

时间:2018-11-22 07:36:50

标签: sql sql-server tsql inner-join

快速浏览一下,是否有以前与我的问题有关的问题,看不到任何问题。

基本上,我正在为在线Cert IV课程做这个数据库,如果我没有完全陷入困境(就像过去几个月一样),我不会在此方面寻求重大帮助

我有一个Antiques数据库,该数据库应该显示客户名称,销售日期,产品名称和销售价格,并且仅列出在2个日期之间出售的商品,并按所述日期进行订购。我没有导致没有重复数据的情况

对于此特定查询,我有4个表客户,销售和产品,表的设置如下:

CREATE TABLE [dbo].[Customers](
[CustID] [int] IDENTITY(1,1) NOT NULL,
[firstName] [varchar](50) NOT NULL,
[lastName] [varchar](50) NOT NULL,
CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED

CREATE TABLE [dbo].[Sales](
[SalesNo] [int] IDENTITY(1,1) NOT NULL,
[CustID] [int] NOT NULL,
[salesDate] [date] NOT NULL,
CONSTRAINT [PK_Sales] PRIMARY KEY CLUSTERED

CREATE TABLE [dbo].[Products](
[ProductID] [int] IDENTITY(1,1) NOT NULL,
[prodName] [varchar](50) NOT NULL,
[prodYear] [int] NOT NULL,
[prodType] [varchar](50) NOT NULL,
[salesPrice] [money] NOT NULL,
CONSTRAINT [PK_Products] PRIMARY KEY CLUSTERED

CREATE TABLE [dbo].[ProductSales](
[ProductID] [int] NOT NULL,
[SalesNo] [int] NOT NULL

我的查询如下

SELECT (Customers.firstName + ' ' + Customers.lastName) AS Customers_Name,
    Sales.salesDate, Products.prodName, Sales.salesPrice
FROM Customers, ProductSales JOIN Products ON ProductSales.ProductID = Products.ProductID
                             JOIN Sales ON ProductSales.SalesNo = Sales.SalesNo
WHERE Sales.salesDate BETWEEN '2016-06-03' AND '2016-06-06'
ORDER BY Sales.salesDate

这是我运行此查询时显示的内容:

Queried Data

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

尝试以下方法-您需要正确加入客户表

SELECT (Customers.firstName + ' ' + Customers.lastName) AS Customers_Name,
    Sales.salesDate, Products.prodName, Sales.salesPrice
FROM ProductSales JOIN Products ON ProductSales.ProductID = Products.ProductID
                             JOIN Sales ON ProductSales.SalesNo = Sales.SalesNo
JOIN Customers on  Sales.[CustID]=Customers.[CustID]
WHERE Sales.salesDate BETWEEN '2016-06-03' AND '2016-06-06'
ORDER BY Sales.salesDate