E
E
ellz2019-02-17 20:09:17
Transact SQL
ellz, 2019-02-17 20:09:17

Why is the query duplicate data?

There is a request like this:

SELECT
HotelsRooms.roomTypeID as RoomType,
HotelsRooms.price * 5  + tours.Price as Price
FROM dbo.HotelsRooms 
INNER JOIN dbo.Hotels as hotels ON HotelsRooms.HotelID = hotels.Id
INNER JOIN dbo.Tours as tours ON tours.HotelID = hotels.Id
WHERE hotels.Name = N'Mountview Lodge Apt'

It duplicates the result.
If you remove JOIN Tours, then everything will be fine. But I need the Tours entity.
Example

С join:
RoomType Price
1	50500
2	57875
3	56400
4	61415
5	63775
1	50500
2	57875
3	56400
4	61415
5	63775

Без join
RoomType Price
1	50500
2	57875
3	56400
4	61415
5	63775

Tables:

Tours:
CREATE TABLE [dbo].[Tours] (
    [Id]       INT  IDENTITY (1, 1) NOT NULL,
    [HotelID]  INT  NOT NULL,
    [FromDate] DATE NOT NULL,
    [ToDate]   DATE NOT NULL,
    [Price]    INT  NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

Cities:
CREATE TABLE [dbo].[Cities] (
    [Id]        INT           IDENTITY (1, 1) NOT NULL,
    [Name]      NVARCHAR (90) NOT NULL,
    [CountryID] INT           NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

Countrys:
CREATE TABLE [dbo].[Countrys] (
    [Id]   INT           IDENTITY (1, 1) NOT NULL,
    [Name] NVARCHAR (90) NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

Hotels:
CREATE TABLE [dbo].[Hotels] (
    [Id]                INT            IDENTITY (1, 1) NOT NULL,
    [City]              INT            NOT NULL,
    [Rating]            INT            NOT NULL,
    [Name]              NVARCHAR (60)  NOT NULL,
    [DistanceToBeach]   INT            NULL,
    [Line]              INT            NULL,
    [DistanceToAirport] INT            NOT NULL,
    [Discription]       NVARCHAR (MAX) NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

HotelsRooms:
CREATE TABLE [dbo].[HotelsRooms] (
    [Id]         INT IDENTITY (1, 1) NOT NULL,
    [HotelID]    INT NOT NULL,
    [roomTypeID] INT NOT NULL,
    [price]      INT NOT NULL,
    [count]      INT NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

HotelsRommTypes:
CREATE TABLE [dbo].[HotelRoomTypes] (
    [Id]         INT IDENTITY (1, 1) NOT NULL,
    [SingleBeds] INT NULL,
    [DoubleBeds] INT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
luna3956, 2019-02-17
@ellz

Because in the Tours table one hotel can appear more than once, depending on the dates of the tour (fromDate AND toDate). If you have a fixed price for any dates, then join not the Tours table, but this:

...
inner join (select distinct hotelId,price from Tours)

If the price can be different depending on the dates, then the "duplication" that has occurred is logically correct. just add date output from the Tours table to your query and see

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question