There are some tables that we want to do a search.
I couldn't understand why this error happens , please help.
I should be easy for experts,
SELECT * FROM passenger
INNER JOIN [passenger-flylist] ppff
ON ppp.[passenger-id] = ppff.[passenger-id]
the Error :
Msg 4104, Level 16, State 1, Line 1
The multi-part identifier "ppp.passenger-id" could not be bound.
Tables are :
CREATE TABLE [dbo].[passenger](
[passenger-id] [int] IDENTITY(1,1) NOT NULL,
[name] [char](50) COLLATE Arabic_CI_AS NOT NULL,
[sex] [char](10) COLLATE Arabic_CI_AS NULL,
[mobile] [char](20) COLLATE Arabic_CI_AS NULL,
[address] [varchar](50) COLLATE Arabic_CI_AS NULL,
[flylist-id] [int] NOT NULL,
[chair-number] [char](10) COLLATE Arabic_CI_AS NOT NULL,
[Age] [char](10) COLLATE Arabic_CI_AS NULL,
[ticket-number] [char](10) COLLATE Arabic_CI_AS NULL,
CONSTRAINT [PK_passenger] PRIMARY KEY CLUSTERED
(
[passenger-id] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
Second
CREATE TABLE [dbo].[flylist](
[flylist-id] [int] IDENTITY(1,1) NOT NULL,
[fly-number] [varchar](50) COLLATE Arabic_CI_AS NOT NULL,
[go-date] [char](15) COLLATE Arabic_CI_AS NOT NULL,
[return-date] [char](15) COLLATE Arabic_CI_AS NOT NULL,
[go-time] [char](5) COLLATE Arabic_CI_AS NOT NULL,
[return-time] [char](5) COLLATE Arabic_CI_AS NOT NULL,
[start-from] [varchar](50) COLLATE Arabic_CI_AS NOT NULL,
[destination] [varchar](50) COLLATE Arabic_CI_AS NULL,
[airline-company-id] [int] NOT NULL,
[airplane-id] [int] NOT NULL,
CONSTRAINT [PK_flylist] PRIMARY KEY CLUSTERED
(
[flylist-id] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
Third
CREATE TABLE [dbo].[passenger-flylist](
[passenger-id] [int] NOT NULL,
[flylist-id] [int] NOT NULL,
CONSTRAINT [PK_passenger-flylist] PRIMARY KEY CLUSTERED
(
[passenger-id] ASC,
[flylist-id] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
USE [AirlineSx]
GO
ALTER TABLE [dbo].[passenger-flylist] WITH CHECK ADD CONSTRAINT [FK_passenger-flylist_passenger-flylist] FOREIGN KEY([passenger-id], [flylist-id])
REFERENCES [dbo].[passenger-flylist] ([passenger-id], [flylist-id])
If I had problem in setting the relations , please tell me how to do ,
thanks
Edited Part
Thanks , I found that in parallel with you , but I got another error :
( In my real code I want to get Passenger-id , but it doesn't allow me )
SELECT [passenger-id] FROM passenger ppp -- <<<< This line
INNER JOIN [passenger-flylist] ppff
ON ppp.[passenger-id] = ppff.[passenger-id]
INNER JOIN flylist fff ON ppff.[flylist-id] = fff.[flylist-id]
WHERE ppp.[name] = #name AND
fff.[start-from] = #flightDate AND
ppp.[ticket-number] = #ticketNo
The Error is:
Msg 209, Level 16, State 1, Procedure SearchForPassenger, Line 19
Ambiguous column name 'passenger-id'.
It refers to the 1st line that we want to select [passenger-id]
The problem is a missing alias ppp
SELECT * FROM passenger ppp
INNER JOIN [passenger-flylist] ppff
ON ppp.[passenger-id] = ppff.[passenger-id]
As to the second problem...
As passenger-id exists in both passenger and passenger-flylist you need to specify the alias of the table.
SELECT ppp.[passenger-id] FROM passenger ppp
INNER JOIN [passenger-flylist] ppff
ON ppp.[passenger-id] = ppff.[passenger-id]
INNER JOIN flylist fff ON ppff.[flylist-id] = fff.[flylist-id]
WHERE ppp.[name] = #name AND
fff.[start-from] = #flightDate AND
ppp.[ticket-number] = #ticketNo
Related
I have the index IDX_tbl_SpeedRun_StatusTypeID_GameID_CategoryID_LevelID_PlusInclude on table dbo.tbl_SpeedRun below. The exists statement in the query below is taking a while (1m 10s) saying there is a missing index ON [dbo].[tbl_SpeedRun] ([StatusTypeID],[LevelID]).
Why is the exists statement not using the index I created? It already includes the columns [StatusTypeID],[LevelID].
Table:
CREATE TABLE [dbo].[tbl_SpeedRun]
(
[OrderValue] [int] NOT NULL IDENTITY(1,1),
[ID] [varchar] (50) NOT NULL,
[StatusTypeID] [int] NOT NULL,
[GameID] [varchar] (50) NOT NULL,
[CategoryID] [varchar] (50) NOT NULL,
[LevelID] [varchar] (50) NULL,
[SubCategoryVariableValues] [varchar] (1000) NULL,
[PlayerIDs] [varchar] (1000) NULL,
[PlatformID] [varchar] (50) NULL,
[RegionID] [varchar] (50) NULL,
[IsEmulated] [bit] NOT NULL,
[Rank] [int] NULL,
[PrimaryTime] [bigint] NULL,
[RealTime] [bigint] NULL,
[RealTimeWithoutLoads] [bigint] NULL,
[GameTime] [bigint] NULL,
[Comment] [varchar] (MAX) NULL,
[ExaminerUserID] [varchar] (50) NULL,
[RejectReason] [varchar] (MAX) NULL,
[SpeedRunComUrl] [varchar] (2000) NOT NULL,
[SplitsUrl] [varchar] (2000) NULL,
[RunDate] [datetime] NULL,
[DateSubmitted] [datetime] NULL,
[VerifyDate] [datetime] NULL,
[ImportedDate] [datetime] NOT NULL CONSTRAINT [DF_tbl_SpeedRun_ImportedDate] DEFAULT(GETDATE()),
[ModifiedDate] [datetime] NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[tbl_SpeedRun]
ADD CONSTRAINT [PK_tbl_SpeedRun]
PRIMARY KEY NONCLUSTERED ([ID]) WITH (FILLFACTOR=90) ON [PRIMARY]
GO
CREATE CLUSTERED INDEX [IDX_tbl_SpeedRun_OrderValue]
ON [dbo].[tbl_SpeedRun] ([OrderValue]) WITH (FILLFACTOR=90) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IDX_tbl_SpeedRun_StatusTypeID_GameID_CategoryID_LevelID_PlusInclude]
ON [dbo].[tbl_SpeedRun] ([StatusTypeID], [GameID], [CategoryID],[LevelID])
INCLUDE ([SubCategoryVariableValues], [PlayerIDs], [Rank],[PrimaryTime])
GO
Query:
SELECT
CASE
WHEN EXISTS (SELECT 1 FROM dbo.tbl_SpeedRun rn WITH (NOLOCK)
WHERE rn.LevelID = l.ID AND rn.StatusTypeID = 1)
THEN 1
ELSE 0
END
FROM
dbo.tbl_Level l WITH (NOLOCK)
WHERE
l.GameID = 'pd0wq901'
ORDER BY
l.OrderValue
This is the from clause of your subquery:
WHERE rn.LevelID = l.ID AND rn.StatusTypeID = 1
A helpful index for this predicate would involve the two columns, in any order.
Your existing index does not satisfy that requirement. It has columns:
[StatusTypeID], [GameID], [CategoryID], [LevelID])
INCLUDE ([SubCategoryVariableValues], [PlayerIDs], [Rank], [PrimaryTime])
Both columns are here, but buried within others - so the database cannot take advantage of it to speed up the subquery.
Bottom line: creating a large index that involves a lot of columns does not speed up queries by default. Instead, you can analyze each query individually and define the proper optimization.
I am executing the query on SQL server on hosting and it is taking 1 minute and 35 seconds. And the no, of rows of retrieval are 18000. Still it is taking too much time. Query is
select ID,
FirstName,
LastName,
Branch,
EnquiryID,
Course,
College,
Mobile,
ExamID,
EntranceID,
Entrance,
Venue,
RegNo,
VenueID,
Exam,
Gender,
row_number() over (partition by EnquiryID order by ID asc) as AttemptNO
from AGAM_View_AOPList
order by EnquiryID
TABLE SCHEMAS
CREATE TABLE [dbo].[AGAM_AceOFPace](
[ID] [int] IDENTITY(1,1) NOT NULL,
[EnquiryID] [int] NULL,
[FirstName] [nvarchar](100) NULL,
[MiddleName] [nvarchar](100) NULL,
[LastName] [nvarchar](100) NULL,
[BranchID] [int] NULL,
[Branch] [nvarchar](100) NULL,
[CourseID] [int] NULL,
[ExamID] [int] NULL,
[Exam] [nvarchar](200) NULL,
[EntranceID] [int] NULL,
[Entrance] [nvarchar](200) NULL,
[RegNo] [nvarchar](200) NULL,
[EntranceCode] [nvarchar](100) NULL,
[ExamDate] [nvarchar](50) NULL,
[UserID] [nvarchar](100) NULL,
[EntranceFees] [numeric](18, 2) NULL,
[VenueID] [int] NULL,
[Venue] [nvarchar](max) NULL,
[ChequeNumber] [nvarchar](50) NULL,
[Bank] [nvarchar](100) NULL,
[CreatedDate] [datetime] NULL,
CONSTRAINT [PK_AGAM_AceOFPace] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[AGAM_AceOFPace] WITH CHECK ADD CONSTRAINT [FK_AGAM_AceOFPace_AGAM_Inquiry] FOREIGN KEY([EnquiryID])
REFERENCES [dbo].[AGAM_Inquiry] ([ID])
GO
ALTER TABLE [dbo].[AGAM_AceOFPace] CHECK CONSTRAINT [FK_AGAM_AceOFPace_AGAM_Inquiry]
GO
SECOND TABLE
CREATE TABLE [dbo].[AGAM_Inquiry](
[ID] [int] IDENTITY(1,1) NOT NULL,
[RegNo] [nvarchar](200) NULL,
[BranchID] [int] NULL,
[Category] [nvarchar](100) NULL,
[CourseID] [int] NULL,
[EntranceFees] [numeric](18, 2) NULL,
[EntranceID] [int] NULL,
[UserID] [nvarchar](50) NULL,
[Status] [nvarchar](50) NULL,
[ReminderDate] [datetime] NULL,
[Reminder] [nvarchar](150) NULL,
[Mobile] [nvarchar](50) NULL,
[Email] [nvarchar](50) NULL,
[FirstName] [nvarchar](50) NULL,
[MiddleName] [nvarchar](50) NULL,
[LastName] [nvarchar](50) NULL,
[Landline] [nvarchar](50) NULL,
[Address] [nvarchar](100) NULL,
[DOB] [datetime] NULL,
[Gender] [nvarchar](50) NULL,
[PfBatchTime] [nvarchar](50) NULL,
[SourceOfInquiry] [nvarchar](50) NULL,
[ExStudentID] [int] NULL,
[InquiryDate] [datetime] NULL,
[ReceiptNumber] [nvarchar](50) NULL,
[RawID] [int] NULL,
[Deleted] [int] NULL,
[CreatedBy] [nvarchar](50) NULL,
[CreatedDate] [datetime] NULL,
[LastModifiedBy] [nvarchar](50) NULL,
[LastModifiedDate] [datetime] NULL,
[College] [nvarchar](150) NULL,
[Qualification] [nvarchar](150) NULL,
[RptNo] [nvarchar](100) NULL,
CONSTRAINT [PK_AGAM_Inquiry] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[AGAM_Inquiry] WITH CHECK ADD CONSTRAINT [FK_AGAM_Inquiry_AGAM_Branch] FOREIGN KEY([BranchID])
REFERENCES [dbo].[AGAM_Branch] ([ID])
GO
ALTER TABLE [dbo].[AGAM_Inquiry] CHECK CONSTRAINT [FK_AGAM_Inquiry_AGAM_Branch]
GO
ALTER TABLE [dbo].[AGAM_Inquiry] WITH CHECK ADD CONSTRAINT [FK_AGAM_Inquiry_AGAM_Course] FOREIGN KEY([CourseID])
REFERENCES [dbo].[AGAM_Course] ([ID])
GO
ALTER TABLE [dbo].[AGAM_Inquiry] CHECK CONSTRAINT [FK_AGAM_Inquiry_AGAM_Course]
GO
ALTER TABLE [dbo].[AGAM_Inquiry] WITH CHECK ADD CONSTRAINT [FK_AGAM_Inquiry_AGAM_Users] FOREIGN KEY([UserID])
REFERENCES [dbo].[AGAM_Users] ([UserID])
GO
ALTER TABLE [dbo].[AGAM_Inquiry] CHECK CONSTRAINT [FK_AGAM_Inquiry_AGAM_Users]
GO
Can you try with changing the view to this?
SELECT TOP (100) PERCENT
AP.ID,
AP.FirstName,
AP.LastName,
AP.Branch,
AP.EnquiryID,
AC.Name,
AI.College,
AI.Mobile,
AP.ExamID,
AP.EntranceID,
AP.RegNo,
AP.VenueID,
AP.Exam,
AI.Gender,
AP.BranchID,
AP.CourseID,
AP.CreatedDate,
AI.Status,
AP.Entrance,
AP.Venue
FROM dbo.AGAM_AceOFPace AS AP
INNER JOIN dbo.AGAM_Inquiry AS AI ON AI.ID = AP.EnquiryID
INNER JOIN dbo.AGAM_Course as AC on AC.ID = AP.CourseId
ORDER BY AP.EnquiryID
Do you have an index on EnquiryId and CourseID?
Seeing as you are joining, ordering and partitioning by it you really should.
CREATE INDEX IDX_AGAM_AceOFPace_EnquiryID
ON AGAM_AceOFPace (EnquiryID)
CREATE INDEX IDX_AGAM_AceOFPace_CourseID
ON AGAM_AceOFPace (CourseID)
I do have a problem connecting two tables on MSSQL Management studio.
My goal is connect tables by foreign key and if I delete user I want 2nd table entry will be deleted automatically. I plan to use DELETE Cascade method for that.
User:
CREATE TABLE [dbo].[Users](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[Email] [nvarchar](89) NOT NULL,
[Name] [nvarchar](25) NOT NULL,
[Midname] [nvarchar](25) NOT NULL,
[Surname] [nvarchar](25) NOT NULL,
[Phone] [varchar](15) NOT NULL,
[Country] [smallint] NOT NULL,
[Manager] [nvarchar](89) NOT NULL,
[Referrer] [nvarchar](89) NOT NULL,
[Rank] [tinyint] NOT NULL,
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED
(
[Email] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
Email is Primary key
Payments:
CREATE TABLE [dbo].[Investments](
[ID] [bigint] NOT NULL,
[Investor] [nvarchar](89) NOT NULL,
[Sum] [decimal](19, 4) NOT NULL,
[Currency] [smallint] NOT NULL,
[Credit] [decimal](19, 4) NOT NULL,
[CreditRate] [decimal](19, 4) NOT NULL,
[Rate] [tinyint] IDENTITY(1,1) NOT NULL,
[Date] [smalldatetime] NOT NULL,
[Comment] [nvarchar](max) NOT NULL,
CONSTRAINT [PK_Investments] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ID is Primary key
My FK should be like USER->PAYMENTS or PAYMENTS->USER?
When I am trying to connect User -> Payments using foregn key by Email -> Investor, it tell me such error:
The columns in table 'Payments' do not match an existing primary key or UNIQUE constraint.
Could you please explain me where problem is? And what I am doing wrong?
Change your structure to:
CREATE TABLE [dbo].[Users](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[Email] [nvarchar](89) NOT NULL,
[Name] [nvarchar](25) NOT NULL,
[Midname] [nvarchar](25) NOT NULL,
[Surname] [nvarchar](25) NOT NULL,
[Phone] [varchar](15) NOT NULL,
[Country] [smallint] NOT NULL,
[Manager] [nvarchar](89) NOT NULL,
[Referrer] [nvarchar](89) NOT NULL,
[Rank] [tinyint] NOT NULL);
ALTER TABLE [Users]
ADD CONSTRAINT PK_UsersID PRIMARY KEY (ID);
and then
CREATE TABLE [dbo].[Investments](
[ID] [bigint] NOT NULL,
[UserID] [bigint] NOT NULL,
[Sum] [decimal](19, 4) NOT NULL,
[Currency] [smallint] NOT NULL,
[Credit] [decimal](19, 4) NOT NULL,
[CreditRate] [decimal](19, 4) NOT NULL,
[Rate] [tinyint] IDENTITY(1,1) NOT NULL,
[Date] [smalldatetime] NOT NULL,
[Comment] [nvarchar](max) NOT NULL);
ALTER TABLE Investments
ADD CONSTRAINT PK_InstestmentsID PRIMARY KEY (ID);
ALTER TABLE Investments
ADD CONSTRAINT FK_UsersInvestments
FOREIGN KEY (UserID)
REFERENCES Users(ID);
Then join Users.ID on Investments.UserID
I searched for the error message you are seeing (without the table name) and the general consensus
seems to be that a PRIMARY KEY or UNIQUE contraint has not been correctly set in your tables. The error also tells me you are (probably) using SQL Server.
From technet.microsoft.com:
The columns on the primary key side of a foreign key relationship must
participate in either a Primary Key or a Unique Constraint. After
setting up a Primary Key or a Unique constraint for one of the tables
you've selected, you can then define other relationships for that
table.
Check your PRIMARY KEYS in both tables. Without the actual DDL of your tables it's difficult to be of more help.
EDIT: You have Email as the PRIMARY KEY in your Users table but I do not see an Email field in the Investments table. Which fields are you joining on in your contraint?
CREATE TABLE [dbo].[MembershipModule](
[Id] [uniqueidentifier] ROWGUIDCOL NOT NULL,
[ParentId] [uniqueidentifier] NULL,
[TargetId] [int] NULL,
[WebContentId] [uniqueidentifier] NULL,
[Name] [varchar](35) NOT NULL,
[NameUpper] AS (isnull(upper([Name]),'')) PERSISTED NOT NULL,
[UriPrefix] [varchar](max) NULL,
[UriText] [varchar](max) NULL,
[UriComputed] AS ??? PERSISTED,
[Description] [varchar](100) NULL,
[Created] [date] NOT NULL,
[Modified] [datetime2](7) NOT NULL,
[MenuItem] [bit] NOT NULL,
[Enabled] [bit] NOT NULL,
[Position] [smallint] NULL,
CONSTRAINT [PK_MembershipModule] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
So far the UriComputed field is computed like this:
lower(replace(isnull([UriPrefix],'/')+coalesce([UriText],[Name]),' ','-'))
This produces output like the following
Now, I'd want to terminate all UriComputed values with '/'. This would be easily accomplished by adding + '/' to the computed field, except for the fact that "textless" uris, would be terminated like //, which I don't want happening.
since the sql I can put into a computed field is quite limited (and I don't really know the extents of these limitations) I thought I'd ask here how to add this.
basically I want the output in the image to be
/a/login/
/a/announcements/
/a/
/
my closest attempt at doing this has been:
isnull(convert(varchar(MAX),nullif(len(coalesce([UriText],[Name])),0)),'/')
Which does kind of a mess, and adds a number if it should terminate in '/', and adds '/' when it should, what I'd need is the opposite ( that is, '/' when the length is 0, '' otherwise)
If there's an inline if or something like that I could use that would basically be it, but I don't know about that.
Thank you!
This worked for me:
[UriComputed] AS (CASE
WHEN RIGHT(lower(replace(isnull([UriPrefix],'/')+coalesce([UriText],[Name]),' ','-')), 1) = '/' THEN
lower(replace(isnull([UriPrefix],'/')+coalesce([UriText],[Name]),' ','-'))
ELSE
lower(replace(isnull([UriPrefix],'/')+coalesce([UriText],[Name]),' ','-')) +'/'
END) PERSISTED,
Full CREATE TABLE statement:
CREATE TABLE [dbo].[MembershipModule](
[Id] [uniqueidentifier] ROWGUIDCOL NOT NULL,
[ParentId] [uniqueidentifier] NULL,
[TargetId] [int] NULL,
[WebContentId] [uniqueidentifier] NULL,
[Name] [varchar](35) NOT NULL,
[NameUpper] AS (isnull(upper([Name]),'')) PERSISTED NOT NULL,
[UriPrefix] [varchar](max) NULL,
[UriText] [varchar](max) NULL,
[UriComputed] AS (CASE
WHEN RIGHT(lower(replace(isnull([UriPrefix],'/')+coalesce([UriText],[Name]),' ','-')), 1) = '/' THEN
lower(replace(isnull([UriPrefix],'/')+coalesce([UriText],[Name]),' ','-'))
ELSE
lower(replace(isnull([UriPrefix],'/')+coalesce([UriText],[Name]),' ','-')) +'/'
END) PERSISTED,
[Description] [varchar](100) NULL,
[Created] [date] NOT NULL,
[Modified] [datetime2](7) NOT NULL,
[MenuItem] [bit] NOT NULL,
[Enabled] [bit] NOT NULL,
[Position] [smallint] NULL)
i have 3 table (SalesLog, Breakages, SalesReturn), I want to display data from these table like
ProductName SalesQty BreakQty ReturnQty
ABCD 1000 10 20
SalesLog Table
CREATE TABLE [dbo].[SalesLog](
[SalesID] [int] IDENTITY(1,1) NOT NULL,
[MemoNo] [int] NULL,
[ProductCode] [int] NULL,
[Quantity] [int] NULL,
[Price] [int] NULL,
[pGroup] [int] NULL,
[pName] [nvarchar](30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[pSize] [int] NULL,
[BillDate] [nchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
CONSTRAINT [PK_SalesLog] PRIMARY KEY CLUSTERED
(
[SalesID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
Breakages Table
CREATE TABLE [dbo].[Breakages](
[breakId] [int] IDENTITY(1,1) NOT NULL,
[MemoNo] [int] NULL,
[SalesmanID] [int] NULL,
[ProductCode] [int] NULL,
[pName] [nvarchar](30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Quantity] [int] NULL,
[pGroup] [nvarchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[BillDate] [nchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[AddedOn] [datetime] NULL,
CONSTRAINT [PK_Breakages_1] PRIMARY KEY CLUSTERED
(
[breakId] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
SalesReturn Table
CREATE TABLE [dbo].[SalesReturn](
[srID] [int] IDENTITY(1,1) NOT NULL,
[ProductCode] [int] NULL,
[Quantity] [int] NULL,
[pGroup] [int] NULL,
[MemoNo] [int] NULL,
[SalesmanID] [int] NULL,
[Price] [int] NULL,
[BillDate] [nchar](10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[AddedOn] [datetime] NULL,
CONSTRAINT [PK_SalesReturn] PRIMARY KEY CLUSTERED
(
[srID] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
Any help will be appreciated..
Select
pname as ProductName ,
ProductCode as pc
Quantity as SalesQty ,
(select
Quantity
from Breakages
where Breakages.ProductCode = pc
) as BreakQty ,
(select
Quantity
from SalesReturn
where ProductCode = pc) as ReturnQty
from SalesLog;
SELECT
sl.pName,
SUM(sl.Quantity) as TotalQty,
SUM(br.Quantity) as TotalBreakageQty,
SUM(sr.Quantity) as TotalReturnQty
FROM
SalesLog sl
LEFT JOIN Breakages br ON sl.ProductCode = br.ProductCode
LEFT JOIN SalesReturn sr ON sl.ProductCode = sr.ProductCode
GROUP BY
sl.pName
This will give you total quantities grouped by product name.
As AakashM correctly points out, using inner joins will return only records that have a breakage and a return, so I have changed them to left joins.