SQL query taking 1 minute and 35 seconds - sql

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)

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

Slow and fast comparison in Tablediff.exe

I am using tablediff.exe to compare two SQL tables, on two servers one is local and the other is remote.
My first table is Table1 (380,000 records)
My second Table is Table2 (290,000 records)
When I compare local Table1 to remote Table1 it takes about 6 minutes .
When I compare local Table2 to remote Table2 it takes about forever and no result (Table2 has less records than Table1)
I deleted a column of type image from Table2, but the problem still there.
What may be the problem ?
NOTE: TABLE2 Structure
[ID] [varchar](10) NOT NULL,
[Title] [nvarchar](10) NULL,
[FName] [nvarchar](255) NULL,
[MName] [nvarchar](25) NULL,
[LName] [nvarchar](25) NULL,
[MotherName] [nvarchar](25) NULL,
[DOB] [datetime] NULL,
[BirthPlace] [nvarchar](50) NULL,
[Gender] [varchar](1) NULL,
[MaritalStatus] [nvarchar](25) NULL,
[ChildrenNo] [varchar](50) NULL,
[Occupation] [nvarchar](25) NULL,
[NationalityID] [varchar](3) NULL,
[Address] [nvarchar](255) NULL,
[Telephone] [varchar](20) NULL,
[Mobile] [varchar](20) NULL,
[Email] [varchar](50) NULL,
[BloodGroup] [varchar](3) NULL,
[RecieveSMS] [bit] NULL,
[FileNo] [nvarchar](250) NULL,
[PrimaryPhysician] [varchar](10) NULL,
[IqamaID] [varchar](10) NULL,
[EmergencyContactName] [nvarchar](50) NULL,
[EmergencyContactRelation] [nvarchar](50) NULL,
[EmergencyContactNo] [nvarchar](50) NULL,
[ProfilePicture] [image] NULL,
[Status] [bit] NULL,
[SecondaryTelNo] [varchar](20) NULL,
[SecondaryMobileNo] [varchar](20) NULL,
[Notes] [nvarchar](255) NULL,
[BankID] [varchar](10) NULL,
[IBANNo] [nvarchar](50) NULL,
[isWalkIn] [bit] NULL CONSTRAINT [DF_Patients_isWalkIn] DEFAULT ((0)),
[AR_FName] [nvarchar](255) NULL,
[AR_MName] [nvarchar](25) NULL,
[AR_LName] [nvarchar](25) NULL,
[AR_MotherName] [nvarchar](25) NULL,
[isVIP] [bit] NULL,
[FirstVisitDate] [varchar](255) NULL,
[EmploymentID] [varchar](20) NULL,
[ImagePath] [nvarchar](250) NULL,
[PatientLevel] [int] NOT NULL CONSTRAINT [DF_Patients_PatientLevel] DEFAULT ((1)),
CONSTRAINT [PK_Patients] 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]

There are no primary or candidate keys in the referenced table 'dbo.CMS_User'

Error
There are no primary or candidate keys in the referenced table
'dbo.CMS_User' that match the referencing column list in the foreign
key 'FK_CMS_UserSettings_User
Query:
ALTER TABLE [dbo].[CMS_UserSettings] WITH CHECK ADD CONSTRAINT [FK_CMS_UserSettings_UserSettingsUserGUID_CMS_User] FOREIGN KEY([UserSettingsUserGUID])
REFERENCES [dbo].[CMS_User] ([UserGUID])
ON UPDATE CASCADE
GO
ALTER TABLE [dbo].[CMS_UserSettings] CHECK CONSTRAINT [FK_CMS_UserSettings_UserSettingsUserGUID_CMS_User]
GO
I am getting the above error while i execute statements
Could you please help me how to create a contraint here, what going wrong while i create it?
CREATE TABLE [dbo].[CMS_UserSettings](
[UserSettingsID] [int] IDENTITY(1,1) NOT NULL,
[UserNickName] [nvarchar](200) NULL,
[UserPicture] [nvarchar](200) NULL,
[UserSignature] [nvarchar](max) NULL,
[UserURLReferrer] [nvarchar](450) NULL,
[UserCampaign] [nvarchar](200) NULL,
[UserMessagingNotificationEmail] [nvarchar](200) NULL,
[UserCustomData] [nvarchar](max) NULL,
[UserRegistrationInfo] [nvarchar](max) NULL,
[UserPreferences] [nvarchar](max) NULL,
[UserActivationDate] [datetime2](7) NULL,
[UserActivatedByUserID] [int] NULL,
[UserTimeZoneID] [int] NULL,
[UserAvatarID] [int] NULL,
[UserBadgeID] [int] NULL,
[UserActivityPoints] [int] NULL,
[UserForumPosts] [int] NULL,
[UserBlogComments] [int] NULL,
[UserGender] [int] NULL,
[UserDateOfBirth] [datetime2](7) NULL,
[UserMessageBoardPosts] [int] NULL,
[UserSettingsUserGUID] [uniqueidentifier] NOT NULL CONSTRAINT [DEFAULT_CMS_UserSettings_UserSettingsUserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000'),
[UserSettingsUserID] [int] NOT NULL CONSTRAINT [DEFAULT_CMS_UserSettings_UserSettingsUserID] DEFAULT ((0)),
[WindowsLiveID] [nvarchar](50) NULL,
[UserBlogPosts] [int] NULL,
[UserWaitingForApproval] [bit] NULL CONSTRAINT [DEFAULT_CMS_UserSettings_UserWaitingForApproval] DEFAULT ((0)),
[UserDialogsConfiguration] [nvarchar](max) NULL,
[UserDescription] [nvarchar](max) NULL,
[UserUsedWebParts] [nvarchar](1000) NULL,
[UserUsedWidgets] [nvarchar](1000) NULL,
[UserFacebookID] [nvarchar](100) NULL,
[UserAuthenticationGUID] [uniqueidentifier] NULL,
[UserSkype] [nvarchar](100) NULL,
[UserIM] [nvarchar](100) NULL,
[UserPhone] [nvarchar](26) NULL,
[UserPosition] [nvarchar](200) NULL,
[UserLinkedInID] [nvarchar](100) NULL,
[UserLogActivities] [bit] NULL,
[UserPasswordRequestHash] [nvarchar](100) NULL,
[UserInvalidLogOnAttempts] [int] NULL CONSTRAINT [DEFAULT_CMS_UserSettings_UserInvalidLogOnAttempts] DEFAULT ((0)),
[UserInvalidLogOnAttemptsHash] [nvarchar](100) NULL,
[UserAvatarType] [nvarchar](200) NULL,
[UserAccountLockReason] [int] NULL CONSTRAINT [DEFAULT_CMS_UserSettings_UserAccountLockReason] DEFAULT ((0)),
[UserPasswordLastChanged] [datetime2](7) NULL,
[UserDataComUser] [nvarchar](200) NULL,
[UserDataComPassword] [nvarchar](200) NULL,
[UserShowIntroductionTile] [bit] NULL,
[UserDashboardApplications] [nvarchar](max) NULL,
[UserDismissedSmartTips] [nvarchar](max) NULL,
CONSTRAINT [PK_CMS_UserSettings] PRIMARY KEY CLUSTERED
(
[UserSettingsID] 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]
GO
ALTER TABLE [dbo].[CMS_UserSettings] WITH CHECK ADD CONSTRAINT [FK_CMS_UserSettings_UserActivatedByUserID_CMS_User] FOREIGN KEY([UserActivatedByUserID])
REFERENCES [dbo].[CMS_User] ([UserID])
GO
ALTER TABLE [dbo].[CMS_UserSettings] CHECK CONSTRAINT [FK_CMS_UserSettings_UserActivatedByUserID_CMS_User]
GO
ALTER TABLE [dbo].[CMS_UserSettings] WITH CHECK ADD CONSTRAINT [FK_CMS_UserSettings_UserAvatarID_CMS_Avatar] FOREIGN KEY([UserAvatarID])
REFERENCES [dbo].[CMS_Avatar] ([AvatarID])
GO
ALTER TABLE [dbo].[CMS_UserSettings] CHECK CONSTRAINT [FK_CMS_UserSettings_UserAvatarID_CMS_Avatar]
GO
ALTER TABLE [dbo].[CMS_UserSettings] WITH CHECK ADD CONSTRAINT [FK_CMS_UserSettings_UserBadgeID_CMS_Badge] FOREIGN KEY([UserBadgeID])
REFERENCES [dbo].[CMS_Badge] ([BadgeID])
GO
ALTER TABLE [dbo].[CMS_UserSettings] CHECK CONSTRAINT [FK_CMS_UserSettings_UserBadgeID_CMS_Badge]
GO
ALTER TABLE [dbo].[CMS_UserSettings] WITH CHECK ADD CONSTRAINT [FK_CMS_UserSettings_UserSettingsUserGUID_CMS_User] FOREIGN KEY([UserSettingsUserGUID])
REFERENCES [dbo].[CMS_User] ([UserGUID])
ON UPDATE CASCADE
GO
ALTER TABLE [dbo].[CMS_UserSettings] CHECK CONSTRAINT [FK_CMS_UserSettings_UserSettingsUserGUID_CMS_User]
GO
ALTER TABLE [dbo].[CMS_UserSettings] WITH CHECK ADD CONSTRAINT [FK_CMS_UserSettings_UserSettingsUserID_CMS_User] FOREIGN KEY([UserSettingsUserID])
REFERENCES [dbo].[CMS_User] ([UserID])
GO
ALTER TABLE [dbo].[CMS_UserSettings] CHECK CONSTRAINT [FK_CMS_UserSettings_UserSettingsUserID_CMS_User]
GO
ALTER TABLE [dbo].[CMS_UserSettings] WITH CHECK ADD CONSTRAINT [FK_CMS_UserSettings_UserTimeZoneID_CMS_TimeZone] FOREIGN KEY([UserTimeZoneID])
REFERENCES [dbo].[CMS_TimeZone] ([TimeZoneID])
GO
ALTER TABLE [dbo].[CMS_UserSettings] CHECK CONSTRAINT [FK_CMS_UserSettings_UserTimeZoneID_CMS_TimeZone]
GO
CREATE TABLE [dbo].[CMS_User](
[UserID] [int] IDENTITY(1,1) NOT NULL,
[UserName] [nvarchar](100) NOT NULL CONSTRAINT [DEFAULT_CMS_User_UserName] DEFAULT (''),
[FirstName] [nvarchar](100) NULL,
[MiddleName] [nvarchar](100) NULL,
[LastName] [nvarchar](100) NULL,
[FullName] [nvarchar](450) NULL,
[Email] [nvarchar](254) NULL,
[UserPassword] [nvarchar](100) NOT NULL CONSTRAINT [DEFAULT_CMS_User_UserPassword] DEFAULT (N''),
[PreferredCultureCode] [nvarchar](10) NULL,
[PreferredUICultureCode] [nvarchar](10) NULL,
[UserEnabled] [bit] NOT NULL CONSTRAINT [DEFAULT_CMS_User_UserEnabled] DEFAULT ((0)),
[UserIsExternal] [bit] NULL CONSTRAINT [DEFAULT_CMS_User_UserIsExternal] DEFAULT ((0)),
[UserPasswordFormat] [nvarchar](10) NULL,
[UserCreated] [datetime2](7) NULL,
[LastLogon] [datetime2](7) NULL,
[UserStartingAliasPath] [nvarchar](200) NULL,
[UserGUID] [uniqueidentifier] NOT NULL,
[UserLastModified] [datetime2](7) NOT NULL,
[UserLastLogonInfo] [nvarchar](max) NULL,
[UserIsHidden] [bit] NULL CONSTRAINT [DEFAULT_CMS_User_UserIsHidden] DEFAULT ((0)),
[UserVisibility] [nvarchar](max) NULL,
[UserIsDomain] [bit] NULL CONSTRAINT [DEFAULT_CMS_User_UserIsDomain] DEFAULT ((0)),
[UserHasAllowedCultures] [bit] NULL,
[UserTokenID] [uniqueidentifier] NULL,
[UserMFRequired] [bit] NULL,
[UserTokenIteration] [int] NULL,
[CountryCode] [nvarchar](2) NULL CONSTRAINT [DEFAULT_CMS_User_CountryCode] DEFAULT (N'US'),
[UserPrivilegeLevel] [int] NULL,
[UserSecurityStamp] [nvarchar](72) NULL,
CONSTRAINT [PK_CMS_User] PRIMARY KEY CLUSTERED
(
[UserID] 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]
GO

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?

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.