Speed up Group By and count SQL query - sql

I am counting/grouping about 1.3 million records with the statement below. The query works but is taking about a minute and a half, which is way too long for my application.
The goal is to get a one each (no duplicates) of the listed fields. The current query returns around 846 rows. I don't have any indexes so far, nor do I know much about adding them.
SELECT
[OfferId]
,[Name]
,COUNT([Name]) AS 'Count'
,[Offer]
,[Title]
,[Text]
,[Amount]
,[Start]
,[End]
,[Image]
,[ImageText]
,[Type]
,[Disclaimer]
,[Link]
,[Status]
FROM
ClientDB.[dbo].[Offers]
GROUP BY
[OfferId]
,[Name]
,[Offer]
,[Title]
,[Text]
,[Amount]
,[Start]
,[End]
,[Image]
,[ImageText]
,[Type]
,[Disclaimer]
,[Link]
,[Status]
Table structure (not sure how to index this to make it faster):
CREATE TABLE [dbo].[Offers]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[Company] [nvarchar](max) NULL,
[Property] [nvarchar](max) NULL,
[Account] [int] NULL,
[OfferID] [nvarchar](50) NULL,
[Offer] [nvarchar](50) NULL,
[Title] [nvarchar](30) NULL,
[Text] [nvarchar](max) NULL,
[AwardCode] [nvarchar](150) NULL,
[Amount] [decimal](18, 2) NULL,
[Start] [datetime] NULL,
[End] [datetime] NULL,
[Image] [nvarchar](max) NULL,
[ImageText] [nvarchar](250) NULL,
[Type] [nvarchar](50) NULL,
[CampaignTier] [nvarchar](50) NULL,
[Name] [nvarchar](max) NULL,
[Disclaimer] [nvarchar](max) NULL,
[Status] [nvarchar](100) NULL,
CONSTRAINT [PK_Offers]
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] TEXTIMAGE_ON [PRIMARY]

I added indexes to the fields I was grouping together and this cut the time from a minute and a half to 1 second.

Related

SQL Query to Count the Number of People who qualify required criteria

I am working on a project that has multiple agents and members. Now I have to do the following (through a SQL Query):
Select agents and members under a Parent Agent who have made payments, in full (amounting to total of 430, i.e. 130+150+150) for 3 months.
Each Agent has n-number of members, so for each agent I need to check if all the members have paid their 3month dues.
If dues are paid, return the total member count agent wise for the parent agent.
I have tried the following query, but no luck:
CREATE TABLE [dbo].[SlipDetails](
[SlipDetailsID] [int] IDENTITY(1,1) NOT NULL,
[SlipID] [int] NULL,
[SlipNumber] [nvarchar](50) NULL,
[AgentID] [int] NULL,
[AgentName] [nvarchar](50) NULL,
[MemberID] [int] NULL,
[MemberName] [nvarchar](50) NULL,
[MonthID] [int] NULL,
[MonthAmount] [int] NULL,
[LateFine] [int] NULL,
[SubmittedDateByAgent] [datetime] NULL,
[ApprovedByAdmin] [nvarchar](1) NULL,
[ApprovedDate] [datetime] NULL,
[MonthName] [nvarchar](50) NULL,
[Blocked] [nvarchar](1) NULL,
CONSTRAINT [PK_SlipDetails] PRIMARY KEY CLUSTERED
(
[SlipDetailsID] 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
CREATE TABLE [dbo].[MemberMaster](
[MemberID] [int] IDENTITY(1,1) NOT NULL,
[MemberName] [nvarchar](50) NULL,
[MemberMobile] [varchar](50) NULL,
[MemberEmail] [nvarchar](50) NULL,
[MemberDOB] [nvarchar](50) NULL,
[MemberDOJ] [nvarchar](50) NULL,
[MemberGender] [nvarchar](50) NULL,
[MemberGenderID] [int] NULL,
[MemberAddress] [nvarchar](50) NULL,
[MemberPhoto] [nvarchar](50) NULL,
[IsFreeGift] [int] NULL,
[GiftID] [int] NULL,
[GiftName] [nvarchar](50) NULL,
[AgentID] [int] NULL,
[AgentName] [nvarchar](50) NULL,
[CardID] [int] NULL,
[CardNumber] [nvarchar](50) NULL,
[SID] [int] NULL,
[SName] [nvarchar](50) NULL,
[Custom1] [nvarchar](50) NULL,
[Custom2] [nvarchar](50) NULL,
[IsActive] [nvarchar](1) NULL,
[IsBlocked] [nvarchar](1) NULL,
CONSTRAINT [PK_MemberMaster] PRIMARY KEY CLUSTERED
(
[MemberID] 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
CREATE TABLE [dbo].[AgentMaster](
[AgentID] [int] IDENTITY(1,1) NOT NULL,
[AgentName] [nvarchar](50) NULL,
[Mobile] [nvarchar](50) NULL,
[AgentUserName] [nvarchar](50) NULL,
[AgentPassword] [nvarchar](50) NULL,
[IsActive] [nvarchar](1) NULL,
[ParentAgentID] [int] NULL,
[ParentAgentName] [nvarchar](50) NULL,
[BankName] [nvarchar](50) NULL,
[AccountHolderName] [nvarchar](50) NULL,
[IFSC] [nvarchar](50) NULL,
[BranchName] [nvarchar](50) NULL,
[AccountNo] [nvarchar](50) NULL,
[AgentPhoto] [nvarchar](50) NULL,
[DOJ] [datetime] NULL,
[SelectedInDraw] [nvarchar](1) NULL,
CONSTRAINT [PK_AgentMaster] PRIMARY KEY CLUSTERED
(
[AgentID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Query:
SELECT COUNT(dbo.MemberMaster.MemberID) AS CMemberID
FROM dbo.SlipDetails
INNER JOIN dbo.MemberMaster ON dbo.SlipDetails.MemberID = dbo.MemberMaster.MemberID
WHERE dbo.MemberMaster.AgentID = 203
GROUP BY dbo.MemberMaster.AgentID,
dbo.SlipDetails.MonthAmount
HAVING(SUM(dbo.SlipDetails.MonthAmount) >= 430);
How do I get the Exact Count for the members under each agent? Any help would be great.
Select mm.AgentName,Count(mm.MemberID) as MemberCount from MemberMaster mm
INNER JOIN
(Select AgentID,MemberId from SlipDetails
group by AgentID,MemberID
having Sum(MonthAmount)>=430)sd
on sd.AgentID=mm.AgentID and sd.MemberID=mm.MemberID
Group by mm.AgentID, mm.AgentName
or even:
Select am.AgentName,MemberCount from AgentMaster am
inner join
(Select mm.AgentID,Count(mm.MemberID) as MemberCount from MemberMaster mm
INNER JOIN
(Select AgentID,MemberId from SlipDetails
group by AgentID,MemberID
having Sum(MonthAmount)>=430)sd
on sd.AgentID=mm.AgentID and sd.MemberID=mm.MemberID
Group by mm.AgentID)mm1
on am.AgentID=mm1.AgentID
Try this
WITH SlipDetails_ttl as (
Select st.MemberID, sum(MonthAmount) as MonthAmount_ttl
from SlipDetails as st
group by st.MemberID
having sum(MonthAmount)>=430
)
Select am.AgentID, count(stt.MemberID)
From SlipDetails_ttl as stt
join MemberMaster as mm on mm.MemberID = stt.MemberID
join AgentMaster as am on mm.AgentID = am.AgentID
group by am.AgentID
Give this a try:
SELECT agt.AgentID, COUNT(*)
FROM dbo.AgentMaster agt -- Get all agents
INNER JOIN dbo.MemberMaster mbr ON agt.AgentID = mbr.AgentID -- Get each agents' members
INNER JOIN dbo.SlipDetails slp ON mbr.MemberID = slp.MemberID -- Get payment details for members
GROUP BY agt.AgentID
HAVING(SUM(slp.MonthAmount)) = 430 -- Only return members that have paid 430
A few assumptions/notes:
only looks at each agent's immediate members (not recursive, one level only)
does not factor in 3-month constraint, only checks that 430 has been paid per member

SQL query taking 1 minute and 35 seconds

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)

Conversion failed when converting from a character string to uniqueidentifier - why?

I am getting this error when running:
SELECT *
FROM repsresidents rr
LEFT JOIN
(SELECT *
FROM residents r1
INNER JOIN
(SELECT res_peopleidy AS peopleidy,
min(res_id) AS RES_ID2
FROM residents
WHERE res_active = '1'
GROUP BY res_peopleidy) r2 ON r1.res_id = r2.res_id2) r ON rr.mainpeopleidy = r.res_peopleidy
WHERE rr.communityidy = 1
I believe the problem is on min(res_id) AS RES_ID2 because res_id is a PK.
Here's the schema of residents table
CREATE TABLE [dbo].[Residents](
[RES_ID] [int] IDENTITY(1,1) NOT NULL,
[RES_PeopleIDY] [varchar](50) NOT NULL,
[RES_PhyMoveInDate] [datetime] NULL,
[RES_CurrentUnitNumber] [varchar](50) NULL,
[RES_CommunityIDY] [int] NULL,
[RES_DateStarted] [datetime] NULL,
[RES_NoPart] [int] NULL,
[RES_LastUserUpdated] [int] NULL,
[PER_ID] [int] NULL,
[HEA_ID] [int] NULL,
[LIF_ID] [int] NULL,
[INT_ID] [int] NULL,
[TES_ID] [int] NULL,
[STA_ID] [int] NULL,
[STA_Type] [int] NULL,
[NetworkSet] [int] NULL,
[RES_Active] [int] NULL,
[RES_HasImage] [int] NULL,
[RES_UpdatedImage] [int] NULL,
[RES_Bio] [text] NULL,
[RES_BioUpdate] [datetime] NULL,
[RES_BioUpdateBy] [int] NULL,
[ACT_ID] [int] NULL,
[RES_LobbyBio] [varchar](max) NULL,
[RES_LobbyBioUpdate] [datetime] NULL,
[RES_LobbyBioUpdateBy] [int] NULL,
[RES_DiscNotes1] [varchar](max) NULL,
[RES_DiscNotes2] [varchar](max) NULL,
[RES_DiscNotes3] [varchar](max) NULL,
[RES_DiscNotes4] [varchar](max) NULL,
[RES_DiscNotes5] [varchar](max) NULL,
[RES_ExpiredDate] [datetime] NULL,
[RES_ExpiredUser] [int] NULL,
[RES_FinishedDate] [datetime] NULL,
[RES_TasksSet] [int] NULL,
CONSTRAINT [PK_Residents] PRIMARY KEY CLUSTERED
(
[RES_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] TEXTIMAGE_ON [PRIMARY]
What am I doing wrong?
Since there are no UNIQUEIDENTIFIERS on Residents, I would have to believe that your issue is with RepsResidents. Any chance that mainpeopleidy is a uniqueidentifier?

TSQL Computed column limitations

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)

displaying data from multiple tables

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.