SQL get duplicates created within n seconds, update f key row in other table, delete dups - sql

I have a table InspectionNotes - I am able to get duplicate notes that are created within n seconds - this works well.
Problem is when I try to delete where rn > 1 I hit a foreign key constraint - in
InspectionHoldDurations column PutOnHoldNoteID.
table Inspection Notes:
CREATE TABLE [dbo].[InspectionNotes](
[InspectionNoteID] [uniqueidentifier] NOT NULL,
[InspectionID] [uniqueidentifier] NOT NULL,
[UserRoleID] [uniqueidentifier] NOT NULL,
[Notes] [nvarchar](max) NOT NULL,
[CurrentInspectionStatusID] [int] NOT NULL,
[CreatedOn] [datetime] NOT NULL,
[InspectionNoteTypeID] [int] NOT NULL,
[QuickAnswerID] [uniqueidentifier] NULL,
[Reviewed] [bit] NOT NULL CONSTRAINT [DF_InspectionNotes_Reviewed] DEFAULT ((0)),
[DateReviewed] [datetime] NULL,
[ReviewedByUserRoleID] [uniqueidentifier] NULL,
CONSTRAINT [PK_InspectionNotes] PRIMARY KEY CLUSTERED
Table InspectionHoldDurations
CREATE TABLE [dbo].[InspectionHoldDurations](
[InspectionHoldDurationID] [uniqueidentifier] NOT NULL,
[InspectionID] [uniqueidentifier] NOT NULL,
[PutOnHoldByRoleID] [uniqueidentifier] NOT NULL,
[TookOffHoldByRoleID] [uniqueidentifier] NULL,
[StartDate] [datetime] NOT NULL,
[EndDate] [datetime] NULL,
[TotalHoldDurationMinutes] [int] NULL,
[ExpirationDate] [datetime] NULL,
[PutOnHoldNoteID] [uniqueidentifier] NULL,
[TakeOffHoldNoteID] [uniqueidentifier] NULL,
PRIMARY KEY CLUSTERED
(
[InspectionHoldDurationID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
My current query to delete duplicates:
;WITH CTE1
AS (
SELECT
[InspectionNoteID],
ROW_NUMBER() OVER (partition by InspectionID, Notes,UserRoleID,CurrentInspectionStatusId,InspectionNoteTypeID,QuickAnswerID,Reviewed,DateReviewed,ReviewedByUserRoleID,DATEDIFF(ss,'1/1/1970',CreatedOn) / 10000 ORDER BY createdon ASC) AS rn
FROM [DBO].[InspectionNotes]
)
DELETE inote
FROM
[DBO].[InspectionNotes] inote
INNER JOIN
CTE1
ON inote.InspectionNoteID = CTE1.[InspectionNoteID]
where CTE1.rn > 1
AND NOT EXISTS (SELECT * FROM [DBO].[InspectionHoldDurations] WHERE PutOnHoldNoteID = CTE1.InspectionNoteID or TakeOffHoldNoteID = CTE1.InspectionNoteID)
I want to get rid of the AND NOT EXISTS (SELECT * FROM [DBO].[InspectionHoldDurations] and instead update this table with corresponding row from CTE1 where rn = 1 - then delete from InspectionNotes where rn > 1. I have tried this and keep getting fkey error.

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

Recursive query to speed up system

My application reads a table with parent child relation. The application queries every level of the tree on his own and it really slow (must do multiple levels deep). I has searching for another solution and came to the recursive queries. With the examples that I have found I cannot map it to my data structure.
My structure looks like:
CREATE TABLE [products].[BillOfMaterial](
[id] [bigint] IDENTITY(1,1) NOT NULL,
[parentNumber] [nvarchar](50) NOT NULL,
[warehouse] [nvarchar](50) NOT NULL,
[sequenceNumber] [int] NOT NULL,
[childNumber] [nvarchar](50) NOT NULL,
[childDescription] [nvarchar](50) NULL,
[qtyRequired] [numeric](18, 3) NOT NULL,
[childItemClass] [nvarchar](50) NULL,
[childItemType] [nvarchar](50) NULL,
[scrapFactor] [numeric](18, 3) NULL,
[bubbleNumber] [int] NOT NULL,
[operationNumber] [int] NOT NULL,
[effectivityDate] [date] NULL,
[discontinuityDate] [date] NULL,
[companyID] [bigint] NOT NULL,
CONSTRAINT [PK_BillOfMaterial] 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]
Some example data:
When I query for parentNumber 1 it should give me all those rows:
And for parentNumber 3 the output must be:
Now I need all the children of a parent in a recursive way. How can I achieve this using only sql? (I'm using SQL server)
I tried already using the with statement in sql, but it will now give a lot of results.
WITH bom ( [id]
,[parentNumber]
,[warehouse]
,[sequenceNumber]
,[childNumber]
,[childDescription]
,[qtyRequired]
,[childItemClass]
,[childItemType]
,[scrapFactor]
,[bubbleNumber]
,[operationNumber]
,[effectivityDate]
,[discontinuityDate]
,[companyID] )
AS
(
select * from [CR_ApplicationSuite].[products].[BillOfMaterial] where parentNumber IN ('F611882261', '2912435206')
UNION ALL
select b.* from [CR_ApplicationSuite].[products].[BillOfMaterial] b
INNER JOIN [CR_ApplicationSuite].[products].[BillOfMaterial] c on c.childNumber = b.parentNumber
)
SELECT *
FROM bom
Here's an example that uses a table variable for demonstration purposes.
For a recursive query you need to use the CTE within itself.
I included a rootParentNumber, so it's more obvious what the base parent was.
The WHERE clauses are commented in the example.
Because you can either put a WHERE clause within the Recursive Query, or at the outer query. The former should be faster.
declare #BillOfMaterial TABLE (
[id] [bigint] IDENTITY(1,1) NOT NULL,
[parentNumber] [nvarchar](50) NOT NULL,
[warehouse] [nvarchar](50) NOT NULL,
[sequenceNumber] [int] NOT NULL,
[childNumber] [nvarchar](50) NOT NULL,
[childDescription] [nvarchar](50) NULL,
[qtyRequired] [numeric](18, 3) NOT NULL,
[childItemClass] [nvarchar](50) NULL,
[childItemType] [nvarchar](50) NULL,
[scrapFactor] [numeric](18, 3) NULL,
[bubbleNumber] [int] NOT NULL,
[operationNumber] [int] NOT NULL,
[effectivityDate] [date] NULL,
[discontinuityDate] [date] NULL,
[companyID] [bigint] NOT NULL
);
insert into #BillOfMaterial (parentNumber, childNumber, warehouse, sequenceNumber, qtyRequired, bubbleNumber, operationNumber, companyID) values
('1','2','WH1',1,0,0,0,1),
('2','4','WH1',2,0,0,0,1),
('3','4','WH1',3,0,0,0,1),
('4','5','WH1',4,0,0,0,1),
('5','0','WH1',5,0,0,0,1);
WITH BOM
AS
(
select parentNumber as rootParentNumber, *
from #BillOfMaterial
--where parentNumber IN ('1','3')
union all
select bom.rootParentNumber, b.*
from BOM
INNER JOIN #BillOfMaterial b
on (BOM.childNumber = b.parentNumber and b.childNumber <> '0')
)
SELECT
[rootParentNumber]
,[parentNumber]
,[childNumber]
,[id]
,[warehouse]
,[sequenceNumber]
,[childDescription]
,[qtyRequired]
,[childItemClass]
,[childItemType]
,[scrapFactor]
,[bubbleNumber]
,[operationNumber]
,[effectivityDate]
,[discontinuityDate]
,[companyID]
FROM BOM
--WHERE rootParentNumber IN ('1','3')
ORDER BY [rootParentNumber], [parentNumber], [childNumber]
;

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)

SQL Foreign key issue with Primary Keys

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?

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.