I have 2 tables in a large SQL Database and i need to query across them and I am struggling TBH. Here are the parameters:
Table 1 - Live Policies
Table 2 - Email Addresses
Common Pivot = Client number which is present in both tables.
From Table 1 i need to retrieve the following fields:
Client Number
Ref Number
Name
Postcode
Inception date
Policy Type (= 'PC')
Select Client, Ptype, Ref, Incep, [Name], Postcode from [Live
Policies] where Ptype = 'PC'
This works fine.
From Table 2 i need to retrieve:
Webaddr
My question is how do i return the email address for the required records from the second table by referencing the client number? (client number is the same for all records) The second part of the statement is where i'm getting stuck.. I'm aware of the JOIN statement but if i try this i just get nowhere.. Help most appreciated!
USE a JOIN
select L.Client, L.Ptype, L.Ref, L.Incep, L.[Name], L.Postcode, E.Webaddr
from [Live Policies] as L
JOIN [Email Addresses] as E
ON L.Client = E.Client
where Ptype = 'PC'
Related
I have 3 tables that I'm joining and 2 variables that I'm using in one of the joins.
What I'm trying to do is figure out how to join based on either of the statements but not both.
Here's the current query:
SELECT DISTINCT
WR.Id,
CAL.Id as 'CalendarId',
T.[First Of Month],
T.[Last of Month],
WR.Supervisor,
WR.cd_Manager as [Manager], --Added to search by the Manager--
WR.[Shift] as 'ShiftId'
INTO #Workers
FROM #T T
--Calendar
RIGHT JOIN [dbo].[Calendar] CAL
ON CAL.StartDate <= T.[Last of Month]
AND CAL.EndDate >= T.[First of Month]
--Workers
--This is the problem join
RIGHT JOIN [dbo].[Worker_Filtered]WR
ON WR.Supervisor IN (SELECT Id FROM [dbo].[User] WHERE FullName IN(#Supervisors))
or (WR.Supervisor IN (SELECT Id FROM [dbo].[User] WHERE FullName IN(#Supervisors))
AND WR.cd_Manager IN(SELECT Id FROM [dbo].[User] WHERE FullNameIN(#Manager))) --Added to search by the Manager--
AND WR.[Type] = '333E7907-EB80-4021-8CDB-5380F0EC89FF' --internal
WHERE CAL.Id = WR.Calendar
AND WR.[Shift] IS NOT NULL
What I want to do is either have the result based on the Worker_Filtered table matching the #Supervisor or (but not both) have it matching both the #Supervisor and #Manager.
The way it is now if it matches either condition it will be returned. This should be limiting the returned results to Workers that have both the Supervisor and Manager which would be a smaller data set than if they only match the Supervisor.
UPDATE
The query that I have above is part of a greater whole that pulls data for a supervisor's workers.
I want to also limit it to managers that are under a particular supervisor.
For example, if #Supervisor = John Doe and #Manager = Jane Doe and John has 9 workers 8 of which are under Jane's management then I would expect the end result to show that there are only 8 workers for each month. With the current query, it is still showing all 9 for each month.
If I change part of the RIGHT JOIN to:
WR.Supervisor IN (SELECT Id FROM [dbo].[User] WHERE FullName IN (#Supervisors))
AND WR.cd_Manager IN(SELECT Id FROM [dbo].[User] WHERE FullName IN(#Manager))
Then it just returns 12 rows of NULL.
UPDATE 2
Sorry, this has taken so long to get a sample up. I could not get SQL Fiddle to work for SQL Server 2008/2014 so I am using rextester instead:
Sample
This shows the results as 108 lines. But what I want to show is just the first 96 lines.
UPDATE 3
I have made a slight update to the Sample. this does get the results that I want. I can set #Manager to NULL and it will pull all 108 records, or I can have the correct Manager name in there and it'll only pull those that match both Supervisor and Manager.
However, I'm doing this with an IF ELSE and I was hoping to avoid doing that as it duplicates code for the insert into the Worker table.
The description of expected results in update 3 makes it all clear now, thanks. Your 'problem' join needs to be:
RIGHT JOIN Worker_Filtered wr on (wr.Supervisor in(#Supervisors)
and case when #Manager is null then 1
else case when wr.Manager in(#Manager) then 1 else 0 end
end = 1)
By the way, I don't know what you are expecting the in(#Supervisors) to achieve, but if you're hoping to supply a comma separated list of supervisors as a single string and have wr.Supervisor match any one of them then you're going to be disappointed. This query works exactly the same if you have = #Supervisors instead.
What would be the best way to take values from two different tables like 1st table has the value of Price, where 2nd table has the value of Quantity, and I will multiply Price by Quantity and the calculated values, Total_Price which will be store in table 3 (newly created). At 1st I've tried using FUNCTION, but many error pops out, so I change it to CTE. But my teacher suggest me to not use temporary tables, because when new row data is added to the tables, we need to run the CTE again to update it everytime new record is added. Is there any other method? Thank you.
You can try something like (syntax not verified!):
INSERT INTO Table_3 (Cur_Date,Prod,Qty,Total_Price)
VALUES (GETDATE() ,
<the passed product_ID> ,
<the passed quantity> ,
(SELECT (A.Quantity * B.Price)
FROM Table_1 A ,
Table_2 B
WHERE A.Product = <Your passed product ID>
AND A.Product = B.Product
)
);
The actual phrasing will depend on your DBMS.
I am trying to create one spx which based upon my ID which is 1009 will move 9 columns data to new table:
The old table has 9 columns:
CD_Train
CD_Date
CD_Score
Notes_Train
Notes_Date
Notes_Score
Ann_Train
Ann_Date
Ann_Score
userid - common in both tables
ID - 1009 - only exists in this table
and my new table has:
TrainingID,
TrainingType,
Score,
Date,
Status,
userid
TrainingType will have 3 values: Notes, CD, Ann
and other fields like score will get data from notes_score and so on
and date will get data from notes_date,cd_date depending upon in which column cd training went
status will get value from Notes_Train, cd_train and so on
based upon this, I am lost how should I do it
I tried querying one sql of users table and tried to do the join but I am losing the ground how to fix it
No idea yet, how to fill your column trainingId but the rest can be done by applying some UNION ALL clauses:
INSERT INTO tbl2 (trainingType,Date,Score,Status,userid)
Select 'CD' , CD_date, CD_score, CD_Train, userid FROM tbl1 where CD_date>0
UNION ALL
SELECT 'Notes', Notes_Date, Notes_Score, Notes_Train, userid FROM tbl1 where Notes_date>0
UNION ALL
SELECT 'Ann', Ann_Date, Ann_Score, ANN_Train, userid
FROM tbl1 where Ann_date>0
I don't know as yet whether all columns are filled in each row. That is the reason for the where clauses which should filter out only those rows with relevant data in the three selected columns.
there are two tables 1) participant and 2) logindatetime.
for first time login datetime value along with other user data like,Name, location, contact number, email gets inserted into participant table having datatime column...for any subsequent login of the same user we insert datetime value into logindatetime column to keep the records of how many times the user logged in....now i have to show all the login time (first login time and subsequent login time) in a single column along with name, location, contact I number, email of the same user.
(I do have an identity in participant table).
Have tried following query:
select a.firstname as 'Name', a.Email as 'Email', a.Address1 as 'Location',
a.MobileNo as 'Contact', COALESCE(a.datetime, b.datetime) as DateTime
from eventonline.participant a, eventonline.logindatetime b
where a.Id = b.Rid";
but it show first login time multiple times.
You need to do something like this to fetch the first and then the other logons separately:
select a.firstname as Name, a.Email, a.Address1 as Location,
a.MobileNo as Contact, a.datetime
from eventonline.participant a
union all
select a.firstname as Name, a.Email, a.Address1 as Location,
a.MobileNo as Contact, b.datetime
from eventonline.participant a
join eventonline.logindatetime b on a.Id = b.Rid
It might be easier just to add the first logon to logindatetime
JamesZ's answer gives the solution but a further note on why your approach isn't working. You're joining the two tables and using coalesce(a.DateTime, b.DateTime) to display login time. If the user has logged in before, a.DateTime has a non-null value. coalesce(x,y) only uses y if x is null. But that's not the real problem. The first login-time needs a record of its own in the logindatetime table. If the users logs in 5 times, your logindatetime will have 4 rows and that's all you'll see when joining the two tables. You need to either save the first login time as a row in logindatetime, or use a UNION to force that first login time to be added as an extra row.
I faced the same issue but according to James Z's answer I solved my problem:
select a.start_date as start, a.end_date as end, a.rooms_id as roomid from maintenance a UNION ALL SELECT b.check_in as start, b.check_out as end, b.room_id AS roomid from reservations b
The result of the query from both tables are here:
You could use joins in your sql statement, i just learnt them 3 days ago and they are very useful!
it would look something like this:
SELECT * FROM table1
LEFT JOIN table2 ON table1.column1 = table2.column1
WHERE table1.column1 = '$yourVar';
table1.column1 could be the id, and the corresponding id in the second table can be the id that links it to the first table (Foreign key), it will retrieve the data of the first table and bring all the data of the second table as well that would match the on the ON criteria
All,
I have 2 tables in Access. Let's call them RepQ1 and Des. There are 2 fields in these 2 tables which I am trying to match and get matching records. These 2 fields are of TEXT data type. Following is the query that I am using.
SELECT * FROM RepQ1 LEFT JOIN Des ON Rep.Mat=Des.MatD;
When I run this, I get no result displayed. Please advise.
Check with this query
SELECT * FROM RepQ1 WHERE RepQ1.Mat IN (SELECT DISTINCT MatD FROM Des);