Cannot Query NULL or Empty Values in a Field or column in a table - sql

I have a query that is 99% working, but I cannot query NULL or empty records for
dbo.HUR_STAFF_DEMOGRAPHICS.DEMOGRAPHICS_POSITION = '' OR
dbo.HUR_STAFF_DEMOGRAPHICS.DEMOGRAPHICS_POSITION IS NULL
I tried both, but the SQL statement below returns no rows if I add the lines above. However it DOES query rows for ALL staff that have a location and or position entered into the database, but my goal is to query this information for all staff that have a location and or position in the database, or if have a location and or position is NULL or BLANK (empty).
I queried the Demographics table alone, and I get a total of 1120 records, I also calculated the columns that have BLANK or NULL (so no position title or Location) and that is 316 records.
Sure enough, when I run this query I get 804 records returned, which means the query is not querying Null or empty columns for Location or Position Title.
Can anyone see why the query will not return the null columns?
SELECT DISTINCT
dbo.HUR_STAFF_DEMOGRAPHICS.employee_no,
first_name, last_name, PREFERRED_NAME,
location,
DEMOGRAPHICS_POSITION,
EMPLOYEE_EMAIL,
Location_name,
Description
FROM
dbo.HUR_STAFF_DEMOGRAPHICS,
dbo.HUR_STAFF_INTERLINK,
dbo.HUR_LOCATION,
dbo.HUR_POSITION_CODE,
dbo.HUR_EMAIL_ADDRESS
WHERE
dbo.HUR_STAFF_DEMOGRAPHICS.employee_no = dbo.HUR_STAFF_INTERLINK.employee_no
AND dbo.HUR_STAFF_DEMOGRAPHICS.location = dbo.HUR_LOCATION.Location_no
AND dbo.HUR_STAFF_DEMOGRAPHICS.DEMOGRAPHICS_POSITION = dbo.HUR_POSITION_CODE.POSITION_CODE
AND dbo.HUR_STAFF_DEMOGRAPHICS.EMPLOYEE_NO = dbo.HUR_EMAIL_ADDRESS.EMPLOYEE_NO
AND dbo.HUR_STAFF_DEMOGRAPHICS.employee_status = 'A'
AND dbo.HUR_STAFF_DEMOGRAPHICS.DEMOGRAPHICS_POSITION IS NULL
ORDER BY
last_name
Thanks in advance for your time and expertise.

I believe your issue is that you are joining to the DEMOGRAPHICS_POSITION table on DEMOGRAPHICS_POSITION = POSITION_CODE, but are also looking for DEMOGRAPHICS_POSITION = '' or DEMOGRAPHICS_POSITION = NULL values. Assuming that the DEMOGRAPHICS_POSITION table has no empty code entry, the join to that table will fail for both of these conditions and no record will be returned.
The solution is to change that join to a LEFT JOIN, but the query must be first rewritten to use ANSI join syntax.
Using table aliases is also a good practice to simplify the statement and improve readability.
Try:
SELECT DISTINCT D.employee_no,
first_name,
last_name,
PREFERRED_NAME,
location,
DEMOGRAPHICS_POSITION,
EMPLOYEE_EMAIL,
Location_name,
Description
FROM HUR_STAFF_DEMOGRAPHICS D
JOIN HUR_STAFF_INTERLINK I
ON D.employee_no = I.employee_no
JOIN HUR_LOCATION L
ON D.location = L.Location_no
LEFT JOIN HUR_POSITION_CODE P
ON D.DEMOGRAPHICS_POSITION = P.POSITION_CODE
JOIN HUR_EMAIL_ADDRESS E
ON D.EMPLOYEE_NO = E.EMPLOYEE_NO
WHERE D.employee_status = 'A'
AND (D.DEMOGRAPHICS_POSITION = '' OR D.DEMOGRAPHICS_POSITION IS NULL)
ORDER BY last_name
Alternately, for this particular usage, you can drop the HUR_POSITION_CODE join entirely, along with the corresponding select list references (Is that where Description comes from?)

Related

Find table with only two rows. Access 2016

I'm looking for a query that I can use in MS Access 2016 which will give me all Company ID's that have the values "Iphone" and "Ipad". So all CompanyID that has only two rows with specific values.
CompanyID Product_Name
1 Iphone
1 Ipad
1 Headphones
2 Iphone
2 Galaxy
3 Playstation 4
3 Nintendo Switch
4 Iphone
4 Ipad
In the example table above I will therefore get the CompanyID = 4.
I have tried to use the same logic as in SQL from the this post but Access doesn't allow syntax USING.
The SQL query used in post is:
SELECT CompanyID
FROM DATA AS a
JOIN DATA AS b
USING (CompanyID)
WHERE a.Product_Name = "Iphone"
AND b.Product_Name = "Ipad";
Any feedback is much appreciated.
Since you state:
So all CompanyID that has only two rows with specific values... In the
example table above I will therefore get the CompanyID = 4.
It would seem that you require the CompanyID for which the only two Product_Name values are Ipad & Iphone, with no other values associated with the CompanyID.
To obtain this result, I might suggest the following SQL query:
select t.companyid
from data t
group by t.companyid
having max(t.product_name in ('Iphone','Ipad'))=-1
Which will return:
CompanyID
4
Here, for every record within each group of records associated with a given CompanyID, the expression t.product_name in ('Iphone','Ipad') is evaluated.
This expression will either return True (-1) or False (0).
If all records within the group are either 'Iphone' or 'Ipad', then this expression will return True (-1) for every record, and the maximum over the group will be -1.
Whereas, if any record within the group is some other value, this expression will return False (0) and therefore the maximum of the group will be 0, thus excluding it from the result.
You can use an INNER JOIN to filter the results that do not contain both values:
SELECT a.CompanyID
FROM (
SELECT CompanyID
FROM DATA
WHERE Product_Name = 'IPhone'
) a
INNER JOIN (
SELECT CompanyID
FROM DATA
WHERE Product_Name = 'Ipad'
) b ON b.CompanyID = a.CompanyID
Output:
CompanyID
1
4
How does this work?
Firstly all results that have an IPhone are gathered. Then this is joined with all results that have an IPad. Only results with both rows matching (because of the INNER JOIN) will be returned.
While late to this, it looks like they're only being pulled from one table - DATA. If that's the case then the easiest solution should just be
SELECT DATA.CompanyID
FROM (DATA)
WHERE DATA.Product_Name = "Iphone"
AND DATA.Product_Name = "Ipad";
For Access, the FROM statement is generally only used for combining tables, or queries, and the data manipulation is in the other statements.
If there's more than one table and the connection between the two tables is CompanyID, then it should look more like this;
SELECT DATA1.CompanyID
FROM (DATA1 INNER JOIN DATA1.CompanyID ON DATA2.CompanyID)
WHERE DATA2.Product_Name = "Iphone"
AND DATA2.Product_Name = "Ipad";

Why won't this query update the field with the lookup?

I'm trying to run the following query to update one table from another. The dates and email address work and carry across, but the nested query I'm using to get Subject_1 from a reference table does not. What am I doing wrong?
SELECT
FirstRegistered As SignUpdate,
(SELECT Subj_ClusName FROM tblSubjectLookup INNER JOIN PAD_ApplicantLost2000 ON tblSubjectLookup.Subj_Name=PAD_ApplicantLost2000.raw_subj_interest_1) AS Subject_1,
Email_Address
FROM PAD_ApplicantLost2000
The origin table, PAD_ApplicantLost2000, has a 'raw subject' column which contains, for example, 'Biology'. There is another table, tblSubjectLookup, which has codes for all subjects, so Subj.Name has 'Biology' and 'Subj_ClusName' has 'B1', which is what needs to go in my target table. However, the Subject_1 field in the target table does not populate.
What am I doing wrong?
Why not just use a WHERE clause instead of joining the table again. I also added LIMIT 1 just to make sure only 1 value is returned.
SELECT
FirstRegistered As SignUpdate,
(SELECT Subj_ClusName FROM tblSubjectLookup WHERE tblSubjectLookup.Subj_Name = PAD_ApplicantLost2000.raw_subj_interest_1 LIMIT 1) AS Subject_1,
Email_Address
FROM PAD_ApplicantLost2000
Another, possibly better, way to do it would just be to join the table directly.
SELECT
FirstRegistered As SignUpdate,
Subj_ClusName AS Subject_1,
Email_Address
FROM PAD_ApplicantLost2000
LEFT JOIN tblSubjectLookup ON tblSubjectLookup.Subj_Name = PAD_ApplicantLost2000.raw_subj_interest_1

SQL Where Not Exists Containing Multiple Arguments

I am trying to write a query to retrieve data that only exists in one table, I also have other arguments that need to be addressed I have researched the Syntax but I am not understanding why my other Arguments are not being used. Sorry if this post seems rather inexperienced I have only been using SQL for a month.
/*List the patient id, primary diagnosis and attending physician id for current admissions (no discharge date) in ICU
who haven't had an encounter with their attending physician.*/
PRINT 'GROUP 5 SELECT A';
PRINT '';
SELECT Admissions.PatientID, Admissions.PrimaryDiagnosis, Admissions.AttendingPhysicianID
FROM Admissions
WHERE NOT EXISTS
(SELECT *
FROM Encounters
WHERE (Admissions.PatientID = Encounters.PatientID)) And (Admissions.DischargeDate is NULL) And (Admissions.NursingUnitID = 'ICU');
Based on your description, I am guessing that you need a match on both the patient and the physician. Something like this:
SELECT a.PatientID, a.PrimaryDiagnosis, a.AttendingPhysicianID
FROM Admissions a
WHERE NOT EXISTS (SELECT 1
FROM Encounters e
WHERE a.PatientID = e.PatientID AND
a.AttendingPhysicianID = e.PhysicianID
) And
a.DischargeDate is NULL And a.NursingUnitID = 'ICU';
Notice that the table aliases make the query easier to write and to read.

get Value that does not exist in another table and vice versa

I have two table named lu_timepoint which holds default timepoints and another operational table called tbl_data.
The tbl_data contains details about a candidate and a timepoint when he has to come for lab test. The timepoint will range from -30 mins to 24 hrs
The lu_timepoint table is the lookup table for the default timepoints.
I need to write a query that will check whether the timepoint in tbl_data exist in the lu_timepoint table and if its not there i need have the value as false in a column called checked.
Likewise if the timepoint in the lu_timepoint table does not exist in the tbl_data table i need have the value as false in the column checked. else true in a checked column.
I tried with Left Join however i'm getting more rows count due to incorrect join statement.
below is the code i used to get all the candidate id whose timepoint is not equal to the other table
select distinct PT, PCTPT
from tbl_data s
left join lu_Timepoint t
on s.STUDY = t.Study
where s.PCTPT = t.Timepoint
Data is attached in the below link...
Table Data
If you want to get the records that doesn't exists in the joined tabled and vice versa, you can use FULL OUTER JOIN that display the distinct values from each table.
Specifying the database you are using and providing the tables structures and some of your data will help to build the final query.
I have found out the solution for this. I did a left join with the lu_timepoint table and tbl_data and got the values that does not exist in both the tables.
Below is the query i used.
select Candidate, CPEVENT, Test_Number, DosedTime, DoseTime, ExpectedTime, s.Timepoint as tmpt, t.Timepoint as tmpt1, CASE WHEN t.Timepoint IS NULL THEN 'Not Collected' WHEN s.timepoint IS NULL THEN 'Not Collected' ELSE 'Collected' END as Timepoint_Collection, case when t.timepoint is null THEN s.timepoint WHEN s.timepoint IS NULL THEN t.Timepoint WHEN s.timepoint = t.TIMEPOINT THEN s.timepoint END as Timepoint from vw_data s FULL OUTER JOIN lu_pk_Timepoint t on s.PCTPT = t.Timepoint AND s.STUDY=t.Study

How to get one common value from Database using UNION

2 records in above image are from Db, in above table Constraint are (SID and LINE_ITEM_ID),
SID and LINE_ITEM_ID both column are used to find a unique record.
My issues :
I am looking for a query it should fetch the recored from DB depending on conditions
if i search for PART_NUMBER = 'PAU43-IMB-P6'
1. it should fetch one record from DB if search for PART_NUMBER = 'PAU43-IMB-P6', no mater to which SID that item belong to if there is only one recored either under SID =1 or SID = 2.
2. it should fetch one record which is under SID = 2 only, from DB on search for PART_NUMBER = 'PAU43-IMB-P6', if there are 2 items one in SID=1 and other in SID=2.
i am looking for a query which will search for a given part_number depending on Both SID 1 and 2, and it should return value under SID =2 and it can return value under SID=1 only if the there are no records under SID=2 (query has to withstand a load of Million record search).
Thank you
Select *
from Table
where SID||LINE_ITEM_ID = (
select Max(SID)||Max(LINE_ITEM_ID)
from table
where PART_NUMBER = 'PAU43-IMB-P6'
);
If I understand correctly, for each considered LINE_ITEM_ID you want to return only the one with the largest value for SID. This is a common requirement and, as with most things in SQL, can be written in many different ways; the best performing will depend on many factors, not least of which is the SQL product you are using.
Here's one possible approach:
SELECT DISTINCT * -- use a column list
FROM YourTable AS T1
INNER JOIN (
SELECT T2.LINE_ITEM_ID,
MAX(T2.SID) AS max_SID
FROM YourTable AS T2
GROUP
BY T2.LINE_ITEM_ID
) AS DT1 (LINE_ITEM_ID, max_SID)
ON T1.LINE_ITEM_ID = DT1.LINE_ITEM_ID
AND T1.SID = DT1.max_SID;
That said, I don't recall seeing one that relies on the UNION relational operator. You could easily rewrite the above using the INTERSECT relational operator but it would be more verbose.
Well in my case it worked something like this:
select LINE_ITEM_ID,SID,price_1,part_number from (
(select LINE_ITEM_ID,SID,price_1,part_number from Table where SID = 2)
UNION
(select LINE_ITEM_ID,SID,price_1,part_number from Table SID = 1 and line_item_id NOT IN (select LINE_ITEM_ID,SID,price_1,part_number from Table SID = 2)))
This query solved my issue..........