how to get a record based on max date for each user in different multiple tables - sql

I'm trying to make a query that can select the names, DateOfSpecimenResult,SwabResult,DateOfReleaseOfResult. Heres the Visual Representation:
Table: ContactTracingHeader
| AutoID | Name |
1 Jason
2 Chris
Table: Swab
| PatientNo | DateOfSpecimenCollection | SwabResultID | DateOfReleaseOfResult |
1 05/02/2020 1 05/10/2020
1 06/08/2020 1 06/11/2020
1 07/16/2020 2 07/20/2020
Note: ContactTracingHeader.AutoID = Swab.PatientNo
Table: SwabResult
| AutoID | SwabResult |
1 POSITIVE
2 NEGATIVE
Query Output that I'm trying to make
| AutoID | Name | DateOfSpecimenCollection | SwabResult | DateOfReleaseOfResult |
1 Jason 07/16/2020 NEGATIVE 07/20/2020
2 Chris (BLANK) (BLANK) (BLANK)
Note: Swab.ResultID = SwabResult.AutoID
Here, I'm only trying to show a Name with the latest DateOfSpecimenCollection and then use it as a reference for the 2 other column which is SwabResult and DateOfReleaseOfResult, And Since "Chris" doesn't have a input on the Swab table, his records are blank but his name and AutoID Still appears on the table. The SwabResult shows the NEGATIVE, or POSITIVE depending on the ID from table Swab.
What i have done so far is this:
SELECT
CTH.AutoID,
CTH.Firstname,
CTH.Lastname,
(SELECT MAX(DateOfSpecimenCollection)
FROM Swab
WHERE Swab.PatientNo = CTH.AutoID
) AS DateOfSpecimenCollection,
Swab.SwabResultID,
Swab.DateOfReleaseOfResult
FROM ContactTracingHeader AS CTH LEFT JOIN Swab ON Swab.PatientNo = CTH.AutoID;
This Query gets the latest DateOfSpecimenCollection and Output those who aren't in the Swab table which is correct, however it duplicates the record depending how many SwabResult or DateOfReleaseOfResult it has. Also I tried INNER JOIN the table SwabResult so i can output the SwabResult instead of the ID, However it gave me JOIN Expression not supported Error.
I apologize for the long and confusing explanation and duplicate question as I'm trying to strugge to find some answers on the internet. Thank you!

Need a unique identifier in Swab table. If not already there, autonumber should serve
Consider:
Query1:
SELECT Swab.* FROM Swab WHERE ID IN
(SELECT TOP 1 ID FROM Swab AS Dupe WHERE Dupe.PatientNo=Swab.PatientNo
ORDER BY Dupe.DateOfSpecimenCollection DESC);
Query2
SELECT ContactTracingHeader.AutoID, ContactTracingHeader.Name, Query1.DateOfSpecimenCollection,
SwabResult.SwabResult, Query1.DateOfReleaseOfResult
FROM ContactTracingHeader LEFT JOIN (SwabResult RIGHT JOIN Query1
ON SwabResult.AutoID = Query1.SwabResultID)
ON ContactTracingHeader.AutoID = Query1.PatientNo;
Or this sequence:
Query1:
SELECT Swab.PatientNo, Max(Swab.DateOfSpecimenCollection) AS MaxOfDateOfSpecimenCollection
FROM Swab
GROUP BY Swab.PatientNo;
Query2:
SELECT Swab.PatientNo, Swab.DateOfSpecimenCollection, Swab.SwabResultID,
Swab.DateOfReleaseOfResult
FROM Query1 INNER JOIN Swab
ON (Query1.MaxOfDateOfSpecimenCollection = Swab.DateOfSpecimenCollection)
AND (Query1.PatientNo = Swab.PatientNo);
Query3:
SELECT ContactTracingHeader.AutoID, ContactTracingHeader.Name,
Query2.DateOfSpecimenCollection, SwabResult.SwabResult, Query2.DateOfReleaseOfResult
FROM SwabResult RIGHT JOIN (ContactTracingHeader LEFT JOIN Query2
ON ContactTracingHeader.AutoID = Query2.PatientNo)
ON SwabResult.AutoID = Query2.SwabResultID;

Related

SQL Query : Facing issues to get desired records from different tables

I have two tables
Calendar (Calname, CCode, PCode)
Lookup (LCode, Name)
Calendar table contains records like,
Calname | CCode | PCode
abc | O_R | P_R
xyz | C_R | P_C
Lookup table contains records like,
LCode | Name
O_R | Reporting
C_R | Cross
P_R | Process
P_C | ProcessCross
I have to fetch the records in a way where I can get the name of all codes from lookup table which contains the record rowwise.
Desired Output,
Calname | CCode | PCode | CCodeName | PCodeName
abc | O_R | P_R | Reporting | Process
xyz | C_R | P_C | Cross | ProcessCross
I can not apply simply inner join on the basis of code it will not give me desired output.
I tried to use subquery also but it not worked out somehow,
.
Can anyone help me out with this issue.
Thanks
You can try joining the Calendar table to the Lookup table twice, using each of the two codes.
SELECT
c.Calname,
c.CCode,
c.PCode,
COALESCE(t1.Name, 'NA') AS CCodeName,
COALESCE(t2.Name, 'NA') AS PCodeName
FROM Calendar c
LEFT JOIN Lookup t1
ON c.CCode = t1.LCode
LEFT JOIN Lookup t2
ON c.PCode = t2.LCode
An alternative to Tim's answer would be to use scalar subqueries, which may or may not give you some performance benefit due to scalar subquery caching:
SELECT
c.Calname,
c.CCode,
c.PCode,
COALESCE((SELECT l1.name FROM lookup l1 WHERE c.ccode = l1.lcode), 'NA') AS CCodeName,
COALESCE((SELECT l2.name FROM lookup l2 WHERE c.pcode = l2.lcode), 'NA') AS PCodeName
FROM Calendar c;
I would test both answers to see which one works best for your data.

COUNT() return 0 on certain column

Requirements:I wanted to know how many images that each person have posted.
Therefore I create a table schema as follow.
Table=Person
==========
Id (PK) , Column1, Column2, LId (FK)
Table=ListMaster
============
Id (PK) , LId (Unique)
Table = ListDetail
===========
Id (PK), LId(FK), DataId(FK)
Table = Image
=========
Id (PK), Column1, Column2
and use a query SQL
SELECT Person.Id AS PersonId,
Person.Column1 AS PersonC1,
Person.Column2 AS PersonC2,
COUNT(Image.Id) AS ImageCount
FROM Person
LEFT OUTER JOIN ListMaster ON Person.LId = ListMaster.LId
LEFT OUTER JOIN ListDetail ON ListDetail.LId = ListMaster.LId
LEFT OUTER JOIN Data AS Image ON ListDetail.DataId = Image.Id
GROUP BY Person.Id,
Person.Column1,
Person.Column2
I notice some person's "ImageCount" have "0" although there are images that he have posted before.
Could you please advise me how to fix my query or tell me it is even logically possible to do what I wanted? I suspect I make a mistake regarding my table design.
Sample Data
=======
Table = Person
Id (PK)(bigint identity) | Column1 (nvarchar(max)) | Column2 (nvarchar(max)) | LId (FK) (bigint [null])
1 | Test 1 C1 | Test1 C2 | 1
2 | Test 2 C1 | Test 2 C2 | 2
3 | Test 3 C1 | Test 3 C2 | NULL
4 | Test 4 C1 | Test 4 C4 | 37
Table = ListMaster
Id (PK)(bigint)(identity) | LId (Unique)(bigint)
1 | 1
2 | 2
3 | 37
Table = ListDetail
Id (PK)(bigint identity)| LId(FK)(bigint not null)| DataId(FK)(bigint not null)
1 | 1 | 1
2 | 1 | 2
3 | 2 | 3
4 | 37 | 4
Table = Image
Id (PK)(big int not null)(identity) | Column1 (nvarchar(max)) | Column2 (nvarchar(max))
1 | Location 1 | Dummy Data 1
2 | Location 2 | Dummy Data 2
3 | Location 3 | Dummy Data 3
4 | Location 4 | Dummy Data 4
I expect the COUNT(Image.Id) AS ImageCount should return
2
1
0
1
but it return
2
1
0
0
EDIT 1 : Change the table design
EDIT 2 : Add a sample data
If, as you say, your Image.Id column is declared NOT NULL, the only reason you should get a COUNT(Image.Id) of 0 for a Person would be if your LEFT JOINs do not find any Images for a given Person. In that case, Image.Id in your underlying results will be NULL, and therefore COUNT(Image.id) will be zero. This means that either:
There's a Person who doesn't have any ListMaster entries.
There's a ListMaster which doesn't have any ListDetail entries.
There's a ListDetail entry which doesn't have any Data entries.
...or some combination of the above.
You should be able to quickly check which links are missing by adding COUNTs for the appropriate tables to your existing query:
SELECT Person.Id AS PersonId,
Person.Column1 AS PersonC1,
Person.Column2 AS PersonC2,
-- NEXT TWO COUNTS ADDED FOR DEBUGGING
COUNT(ListMaster.LId) AS ListMasterCount,
COUNT(ListDetail.LId) AS ListDetailCount,
COUNT(Image.Id) AS ImageCount
FROM Person
LEFT OUTER JOIN ListMaster ON Person.LId = ListMaster.LId
LEFT OUTER JOIN ListDetail ON ListDetail.LId = ListMaster.LId
LEFT OUTER JOIN Data AS Image ON ListDetail.DataId = Image.Id
GROUP BY Person.Id,
Person.Column1,
Person.Column2
It looks like your query and data as given should return the values you expect. Is this the actual schema, data, and query, or are you simplifying to make this post? I presume your real data does not include values like "test 1 C1", etc. Did you create a DB with these dummy field names and values to do this test, or are you saying that this is the equivalent of what you really have? If this isn't the actual stuff, it could well be that in simplifying you have left out the thing that's really causing the problem.
When I have a query that does not give the expected results, I try to drop out parts of the query to see where the problem is. Like try with only the first join and see if you get the expected results. If that works, add in the second join, etc. Leave out the GROUP BY and just dump all the records, so you can see the actual records and not just the count.
There are many possible sources of trouble. Maybe the data isn't what you think it is. Maybe one of the joins is using the wrong field. Maybe you're getting in trouble because you have different data types and a conversion is not giving the results you expect. Etc.
Try this to check if all your Id, Column1, Column2 have image
SELECT Person.Id AS PersonId,
Person.Column1 AS PersonC1,
Person.Column2 AS PersonC2,
ListMaster.*,
ListDetail.*,
Data.*
FROM Person
LEFT OUTER JOIN ListMaster ON Person.LId = ListMaster.LId
LEFT OUTER JOIN ListDetail ON ListDetail.LId = ListMaster.LId
LEFT OUTER JOIN Data AS Image ON ListDetail.DataId = Image.Id
ORDER BY Person.Id,
Person.Column1,
Person.Column2

combine 2 sql's from different tables into one query

I have for example as first query: (ararnr = article number)
Select ararnr,ararir,aoarom from ar left join ao ON AR.ARARNR=AO.AOARNR WHERE AR.ARARKD=1389
the second query uses the result from the first column from the first query to search in another table
Select votgan, sum(ststan) as totalStock from vo INNER JOIN st on vo.voarnr=st.starnr where voarnr = ararnr
How could I combine both ?
Please note : Not all articlenumbers from the first query will be found in the second, but I need them in my result.
In the result I need the columns from both queries.
EDIT
for example :
first query returns article numbers and the description:
+---------+--------------+
| ararnr | aoarom |
+---------+--------------+
| a123456 | description1 |
| b123456 | description2 |
| 0123456 | description3 |
+---------+--------------+
second query returns the totalstock for those articles:
+---------+--------------+
| ararnr | totalstock |
+---------+--------------+
| a123456 | 12 |
| b123456 | |
| 0123456 | 6 |
+---------+--------------+
Note the second one doesn't return a value since the articlenumber doesn't exist in this table.
In my result I would like to get the articlenumber with corresponding description and stock.
+---------+--------------+-----------+---------+
| ararnr | aoarom | totalStock| vovoan |
+---------+--------------+-----------+---------+
| a123456 | description1 | 12 | 2 |
| b123456 | description2 | | 1 |
| 0123456 | description3 | 6 | |
+---------+--------------+-----------+---------+
I'm using sql on db2
SECOND EDIT
The first query will select some article numbers (ararnr) from table ar and find the corresponding description (aoarom) in another table ao.
The second query finds the stock (vovoan and sum ststan) from two differend tables vo and st for the article numbers found in the first query.
The result should have the article number with corresponding description with corresponding stock from vo and st
I can't fully understand what you're asking, but another join may assist you.
example:
SELECT ar.ararnr, ar.ararir, ar.ararom, vo.votgan, SUM(vo.ststan) as totalStock
FROM ar LEFT JOIN ao ON [id=id] LEFT JOIN vo ON [id=id]
Because I can't tell what your tables structure are, or what you're really asking for, this is the best response I can give you.
This also may be what you're looking for:
Combining 2 SQL queries and getting result set in one
You can use this query.
SELECT ar.ararnr, ar.ararir, ar.ararom, vo.votgan, SUM(vo.ststan) as totalStock
FROM ar
LEFT JOIN ao ON ao.ararnr = ar.ararnr
LEFT JOIN vo ON vo.voarnr = ao.ararnr
If you are using SQL Server as database then this can be done with help of OUTER APPLY
SELECT ararnr,aoarom ,temp.totalStock
FROM ar
LEFT JOIN ao ON AR.ARARNR=AO.AOARNR
OUTER APPLY(
SELECT sum(ststan) as totalStock
FROM vo
INNER JOIN st on vo.voarnr=st.starnr
where voarnr = ar.ararnr
)temp
WHERE AR.ARARKD=1389
You'd get a much more complete answer if you were to post the table structure and desired result, but..
You can use the first query as a resultset for your second query, and join to it. something like:
Select
votgan,
sum(ststan) as totalStock
from vo
inner join (Select
ararnr,
ararir,
ararom
from ar
left join ao .....) z on vo.voarnr = z.ararnr
EDIT:
Select
votgan,
sum(ststan) as totalStock,
z.ararnr,
z.aoarom
from vo
inner join (Select
ararnr,
ararir,
ararom
from ar
left join ao .....) z on vo.voarnr = z.ararnr

SQL many-to-many select help needed

I have 2 tables
Bid_customer
|bidkey | customerkey
| 1 | 1
| 1 | 2
| 1 | 3
customer_groups
| groupkey | customerkey
| 1 | 1
| 1 | 2
| 1 | 3
What I'm trying to get is a result that will look like
| bidkey | groupkey
| 1 | 1
I've tried a cursor and joins but just don't seem to be able to get what i need any ideas or suggestions
EDIT: customers can belong to more that one group also
I am not sure who meaningful your sample data is. However following is a simple example.
Query:
select distinct b.bidkey, g.gkey
from bidcus b
inner join cusgroup g
on
b.cuskey = g.cuskey
and g.gkey = 10;
Results:
BIDKEY GKEY
1 10
Reference: SQLFIDDLE
In order to have a working Many-to-Many relationship in a database you need to have an intermediary table that defines the relationship so you do not get duplicates or mismatched values.
This select statement will join all bids with all groups because the customer matches.
Select bidkey, groupkey
From customer_groups
Inner Join bid_customer
Where customer_groups.customerkey = Bid_customer.customerkey
Hers is a sample Many to Many Relationship:
For your question:
You will need another table that joins the data. For example, GroupBids
customer_groups and bid_customer would have a one-to-many relationship with GroupBids
You would then do the following select to get your data.
Select bidkey, groupkey
From bid_customer
inner join GroupBids
ON bid_customer.primarykey = GroupBids.idBidKey
inner join customer_groups
ON customer_groups.primarykey = GroupBids.idCustomerGroupkey
This would make sure only related groups and bids are returned

My SQL query within a query

I have 2 tables that I am trying to combine in a specific way
Table 1: ‘part_defs’ Table 2 Items_part_values
in value_defs:
ID | Name
-------------
1 | color
2 | size
3 | weight
in Items_part_values
ItemID | valueID | Value
-------------------------
10 | 1 | red
11 | 1 | blue
What I need is a query where for a given item all the rows from value_defs appear and if they have a value in Items_part_values the value.
So for Item 11 I want
ID | Name | Value
--------------------
1 | color | red
2 | size | NULL
3 | weight | NULL
I’m new to MySQL, in access I would have created a subquery with the ItemID as a parameter and then done a Left Join with value_defs on the result.
Is there a way of doing something similar in MySQL?
Thanks
Use:
SELECT p.id,
p.name,
ipv.value
FROM PART_DEFS p
LEFT JOIN ITEMS_PART_VALUES ipv ON ipv.valueid = p.id
AND ipv.itemid = ?
Replace the "?" with the itemid you want to search for.
This means all the PARTS_DEF rows will be returned, and if the ITEMS_PART_VALUES.valueid matches the PART_DEFS.id value, then the ITEMS_PART_VALUES.value value will be displayed for the item you are looking for. If there's no match, the value column will be NULL for that record.
There's a difference in OUTER JOINs, when specifying criteria in the JOIN vs the WHERE clause. In the JOIN, the criteria is applied before the JOIN occurs while in the WHERE clause the criteria is applied after the JOIN.
Use a left join:
SELECT * FROM Table1 LEFT JOIN Table2 USING (ID);
Edit:
SELECT * FROM part_defs LEFT JOIN Items_part_values ON part_defs.ID = Items_part_values.valueID;