Using the same column with two different parameters SQL server - sql

I'm sorry if I'm not asking this correctly. I need to write a query that goes against a log. in the log there is a column note that tracks the success of each step in a procedure. what I need is if a job order "fjobno" has WCutSuccess... in the note field within a date range and that same job order "fjobno" has ASSYSuccess... in another date range I want to list it. I just can't seem to figure it out. I'm sure its simple. and I'm sure people do it all the time. If some one could point me in the right direction I would appreciate it.
select
inm.fgroup, inm.fpartno, jod.fjobno, sqb.note
from
inmast as inm
left join
jodbom as jod on inm.fpartno = jod.fbompart
left join
sqbclog as sqb on jod.fjobno = sqb.job
where
(inm.fgroup = 'isl' or inm.fgroup = 'iss')
and
(sqb.note = 'WCutSuccess...'
and sqb.stamp between '09/01/2014' and '10/01/2014')
and
(sqb.note = 'ASSYSuccess...'
and sqb.stamp between '10/01/2014' and '10/09/2014')

I changed your query a little so it uses IN instead of col = something or col = somethingelse.
I also changed the way you are choosing ranges in dates.
SELECT inm.fgroup,
inm.fpartno,
jod.fjobno,
sqb.note
FROM inmast AS inm
LEFT JOIN jodbom AS jod
ON inm.fpartno = jod.fbompart
LEFT JOIN sqbclog AS sqb
ON jod.fjobno = sqb.job
WHERE inm.fgroup IN ('isl','iss')
AND (
( sqb.note = 'WCutSuccess...'
AND sqb.stamp >= '20140109'
AND sqb.stamp < '20140111')
OR( sqb.note = 'ASSYSuccess...'
AND sqb.stamp >= '20140110'
AND sqb.stamp < '20140911')
)

Related

SQL query to filter by specific date criteria

SQL query to filter by specific date criteria
SQL Server Management Studio V17.7
Question: I am looking for guidance related to a view on how to select records where the Start_Date falls between a defined date range when either the Admit_Status = 1 or Admit_Status = 0 as shown below:
Criteria should be something like: if admit status = 1 then dbo.PT_ASSIGNMENT.START_DATE >= referral_date to ifnull dbo.PT_ADMISSION.TERMINATION_DATE then now() else dbo.PT_ADMISSION.TERMINATION_DATE or if admit status = 0 then start_date >= referral_date to ifnull dbo.PT_ADMISSION.PROSPECT_TERM_DATE then now() else dbo.PT_ADMISSION.PROSPECT_TERM_DATE
My SQL query (View) excluding the above question:
SELECT dbo.RES_BASIC.RESOURCE_ID,
dbo.PT_ADMISSION.ADMISSION_ID,
dbo.PT_ASSIGNMENT.START_DATE,
(CASE PT_ADMISSION.PROSPECT_ADMIT_DATE WHEN NULL THEN PT_ADMISSION.ADMIT_DATE ELSE PT_ADMISSION.PROSPECT_ADMIT_DATE END) AS REFERRAL_DATE,
dbo.PT_ADMISSION.ADMIT_DATE,
dbo.PT_ADMISSION.PROSPECT_ADMIT_DATE,
dbo.PT_ADMISSION.PROSPECT_TERM_DATE,
dbo.PT_ADMISSION.TERMINATION_DATE,
CASE WHEN PT_ADMISSION.ADMIT_DATE IS NOT NULL THEN 1 ELSE 0 END AS ADMIT_STATUS,
dbo.PT_BASIC.PATIENT_CODE,
dbo.RES_BASIC.NAME_FULL
FROM dbo.PT_BASIC
INNER JOIN dbo.PT_STATUS
ON dbo.PT_BASIC.PATIENT_ID = dbo.PT_STATUS.PATIENT_ID
INNER JOIN dbo.A_PATIENT_STATUS
ON dbo.PT_STATUS.ADMIN_SET_ID = dbo.A_PATIENT_STATUS.ADMIN_SET_ID
AND dbo.PT_STATUS.STATUS_CODE = dbo.A_PATIENT_STATUS.STATUS_CODE
INNER JOIN dbo.O_DATASET
ON dbo.PT_BASIC.DATASET_ID = dbo.O_DATASET.DATASET_ID
INNER JOIN dbo.PT_ADMISSION
ON dbo.PT_BASIC.PATIENT_ID = dbo.PT_ADMISSION.PATIENT_ID
AND dbo.PT_STATUS.ADMISSION_ID = dbo.PT_ADMISSION.ADMISSION_ID
INNER JOIN dbo.PT_ASSIGNMENT
ON dbo.PT_BASIC.PATIENT_ID = dbo.PT_ASSIGNMENT.PATIENT_ID
INNER JOIN dbo.A_ASSIGNMENT_TYPE
ON dbo.PT_ASSIGNMENT.ADMIN_SET_ID = dbo.A_ASSIGNMENT_TYPE.ADMIN_SET_ID
AND dbo.PT_ASSIGNMENT.ASSIGNMENT_TYPE = dbo.A_ASSIGNMENT_TYPE.TYPE_ID
INNER JOIN dbo.RES_BASIC
ON dbo.PT_ASSIGNMENT.RESOURCE_ID = dbo.RES_BASIC.RESOURCE_ID
WHERE (dbo.O_DATASET.DATASET_NAME = 'XXXXXXXXXX')
AND (dbo.A_ASSIGNMENT_TYPE.DESCRIPTION = 'REFERRING PHYSICIAN')
GROUP BY dbo.RES_BASIC.NAME_FIRST + ' ' + dbo.RES_BASIC.NAME_LAST,
dbo.RES_BASIC.RESOURCE_ID,
dbo.PT_ADMISSION.ADMISSION_ID,
dbo.PT_BASIC.PATIENT_CODE,
dbo.PT_ASSIGNMENT.START_DATE,
dbo.PT_ADMISSION.PROSPECT_TERM_DATE,
dbo.PT_ADMISSION.PROSPECT_ADMIT_DATE,
dbo.PT_ADMISSION.TERMINATION_DATE,
dbo.PT_ADMISSION.ADMIT_DATE,
dbo.RES_BASIC.NAME_FULL
You can put pretty much any "if" into a condition with simple AND and OR use.
I am having a hard time mentally parsing your "something like" portion, but to give a generic example.
IF A THEN B ELSE C
can be translated to (A AND B) OR (NOT A AND C)
Note: Bill Braskey's "comment" is also worth considering. If the conditional logic gets complicated enough, it can be less work for the database to UNION queries with simpler conditions. You'd still need the condition in one to be A AND B and the other to be NOT A AND C to apply the conditions appropriately, but you'd be simplifying from the overall condition (especially when you consider "C" could actually be a translation of IF D THEN E ELSE F.
Maybe just take the easy way out and write two queries with the separate requirements and do a union

SQL Server - Need to SUM values in across multiple returned records

In the following query I am trying to get TotalQty to SUM across both the locations for item 6112040, but so far I have been unable to make this happen. I do need to keep both lines for 6112040 separate in order to capture the different location.
This query feeds into a Jasper ireport using something called Java.Groovy. Despite this, none of the PDFs printed yet have been either stylish or stained brown. Perhaps someone could address that issue as well, but this SUM issue takes priority
I know Gordon Linoff will get on in about an hour so maybe he can help.
DECLARE #receipt INT
SET #receipt = 20
SELECT
ent.WarehouseSku AS WarehouseSku,
ent.PalletId AS [ReceivedPallet],
ISNULL(inv.LocationName,'') AS [ActualLoc],
SUM(ISNULL(inv.Qty,0)) AS [LocationQty],
SUM(ISNULL(inv.Qty,0)) AS [TotalQty],
MAX(CAST(ent.ReceiptLineNumber AS INT)) AS [LineNumber],
MAX(ent.WarehouseLotReference) AS [WarehouseLot],
LEFT(SUM(ent.WeightExpected),7) AS [GrossWeight],
LEFT(SUM(inv.[Weight]),7) AS [NetWeight]
FROM WarehouseReceiptDetail AS det
INNER JOIN WarehouseReceiptDetailEntry AS ent
ON det.ReceiptNumber = ent.ReceiptNumber
AND det.FacilityName = ent.FacilityName
AND det.WarehouseName = ent.WarehouseName
AND det.ReceiptLineNumber = ent.ReceiptLineNumber
LEFT OUTER JOIN Inventory AS inv
ON inv.WarehouseName = det.WarehouseName
AND inv.FacilityName = det.FacilityName
AND inv.WarehouseSku = det.WarehouseSku
AND inv.CustomerLotReference = ent.CustomerLotReference
AND inv.LotReferenceOne = det.ReceiptNumber
AND ISNULL(ent.CaseId,'') = ISNULL(inv.CaseId,'')
WHERE
det.WarehouseName = $Warehouse
AND det.FacilityName = $Facility
AND det.ReceiptNumber = #receipt
GROUP BY
ent.PalletId
, ent.WarehouseSku
, inv.LocationName
, inv.Qty
, inv.LotReferenceOne
ORDER BY ent.WarehouseSku
The lines I need partially coalesced are 4 and 5 in the above return.
Create a second dataset with a subquery and join to that subquery - you can extrapolate from the following to apply to your situation:
First the Subquery:
SELECT
WarehouseSku,
SUM(Qty)
FROM
Inventory
GROUP BY
WarehouseSku
Now apply to your query - insert into the FROM clause:
...
LEFT JOIN (
SELECT
WarehouseSKU,
SUM(Qty)
FROM
Inventory
GROUP BY
WarehouseSKU
) AS TotalQty
ON Warehouse.WarehouseSku = TotalQty.WarehouseSku
Without seeing the actual schema DDL it is hard to know the exact cardinality, but I think this will point you in the right direction.

MS Access - SQL LEFT JOIN multiple conditions

I have this code which is working fine except that I need to add one more condition:
SELECT record1.*,
tbl_mpsregion.maintenanceteam,
tbl_mpsregion.regionmps
INTO tbl_sapforecast
FROM tbl_mpsregion
RIGHT JOIN
(
SELECT sap_ip19.*,
dateserial(RIGHT(trim([SAP_IP19].[PlanDate]),4),mid(trim([SAP_IP19].[PlanDate]),4,2),LEFT(trim([SAP_IP19].[PlanDate]),2)) AS [DATE/FORECAST],
tbl_labourstandard.re,
tbl_labourstandard.manning,
tbl_labourstandard.skillset AS skillset,
tbl_regionmapping.maintenanceplant,
tbl_regionmapping.area,
tbl_regionmapping.region AS region,
tbl_regionmapping.onresponse,
[RE]*[Manning]/60 AS hours
FROM (sap_ip19
LEFT JOIN tbl_labourstandard
ON (
LEFT(sap_ip19.[Task list description],3) = tbl_labourstandard.jemenawc)
AND (
sap_ip19.[MntPlan] = cdbl(tbl_labourstandard.supplypoint )))
LEFT JOIN tbl_regionmapping
ON sap_ip19.location = cdbl([Tbl_RegionMapping].[FittersDistricts])) AS record1
ON (
record1.region = [Tbl_MPSRegion].[Region])
AND (
record1.skillset = [Tbl_MPSRegion].[Skillset]) ;
Criteria to add is: If SAP_IP19.MntPlan does not match Tbl_LabourStandard.SupplyPoint then use 0 for Tbl_LabourStandard.SupplyPoint. I am not using Server 2000 so using CASE is not a solution. Have tried IIF and SWITCH but they are not taking query to sleep mode (not evaluating). I read that JOINS with IIF or SWITCH cannot be used. Please help!
You should be able to add if's or switches but you could always handle this with an OR - it's not the most performance friendly but it should get the job done, example below:
LEFT JOIN tbl_labourstandard
ON
(LEFT(sap_ip19.[Task list description],3) = tbl_labourstandard.jemenawc)
AND
((Tbl_LabourStandard.SupplyPoint = SAP_IP19.MntPlan AND
sap_ip19.[MntPlan] = cdbl(tbl_labourstandard.supplypoint))
OR (sap_ip19.[MntPlan] = 0))

SQL Query for all systemusers who's organisationunits has a datevalue < ... with pivot table in between

I have 3 tables,
SystemUsers
OrganisationalUnits
UserOrganisationUnits - Pivot with UserId/OrganisationUnitId foreign keys
All tables have an Active bit column and the OrganisationalUnit table has a CoveredTill datetime column.
I want a list of all UserOrganisationUnits where OrganisationalUnit "CoveredTill" is < x (value doesn't matter as will be set in clr) date and all tables records are active.
So far I've only managed to get unique users from my query so any advice would be much appreciated.
SELECT
SystemUsers.DisplayName, SystemUsers.Email,
OrganisationalUnits.Description, OrganisationalUnits.CoveredTill,
OrganisationalUnits.Id, OrganisationalUnits.ParentId, OrganisationalUnits.TypeId
FROM
SystemUsers
RIGHT OUTER JOIN
OrganisationalUnits ON SystemUsers.Id = OrganisationalUnits.Id
INNER JOIN
UserOrganisationUnits ON SystemUsers.Id = UserOrganisationUnits.Id
WHERE
(OrganisationalUnits.Active = 1)
AND (SystemUsers.Active = 1)
AND (UserOrganisationUnits.Active = 1)
AND (OrganisationalUnits.CoveredTill < '2017-03-31 00:00:00.000')
I randomly set the date as the above since I manually set the covered till date as "2015-03-31 00:00:00.000" on all OrganisationalUnits "CoveredTill" columns.
My aim is to have a single sql query string which I can use in my clr stored procedure to create a list of all users who need to be emailed because there organisational unit is no longer covered and for said email to include which organisational unit hence why just having a unique list of users isn't sufficient.
I already have the email code so it's just the query I'm having issues with.
Edit:-
I had first approached this as needing 3 separate queries which I guess after a bit more testing I'll have to revisit unless someone can spot what I'm doing wrong with the above query?
Edit 2:-
After working through the issue with sarin and preparing to provide him a sql db/query copy I found that some of the joins were pointing towards the wrong ID fields (automatically created from different panes so always be wary of anything they create) so below I've included the final solution. (Which includes a couple extra fields I decided might be useful).
SELECT OrganisationalUnits.Description, OrganisationalUnits.CoveredTill, SystemUsers.DisplayName, SystemUsers.Email,
UserOrganisationUnits.LastVisited AS UOULastVisited, SystemUsers.LastVisited AS SULastVisited
FROM UserOrganisationUnits INNER JOIN
OrganisationalUnits ON UserOrganisationUnits.OrganisationUnitId = OrganisationalUnits.Id INNER JOIN
SystemUsers ON UserOrganisationUnits.UserId = SystemUsers.Id
WHERE (OrganisationalUnits.Active = 1) AND (SystemUsers.Active = 1) AND (UserOrganisationUnits.Active = 1) AND
(OrganisationalUnits.CoveredTill < '2017-03-31 00:00:00.000')
Performing a Right\left join before you do an inner join can give you unexpected results as it may produce nulls and your inner join will then attempt to filter them out. I'm not entirely clear about the relationships between the tables but can you turn them all into INNER JOINS to get the same list and produce you a similar result based on your expected outcome?
"My aim is.... to create a list of all users who need to be emailed because there organisational unit is no longer covered"
UPDATED:
SELECT
SystemUsers.DisplayName, SystemUsers.Email,
OrganisationalUnits.Description, OrganisationalUnits.CoveredTill,
OrganisationalUnits.Id, OrganisationalUnits.ParentId, OrganisationalUnits.TypeId
FROM
UserOrganisationUnits
INNER JOIN SystemUsers ON SystemUsers.Id = UserOrganisationUnits.Id
AND (SystemUsers.Active = 1)
INNER JOIN OrganisationalUnits ON OrganisationalUnits.Id = SystemUsers.Id
AND OrganisationalUnits.Active = 1
AND OrganisationalUnits.CoveredTill < '2017-03-31 00:00:00.000'
WHERE UserOrganisationUnits.Active = 1

SQL query for filtering data

I`m working on some sql queries to get some data out of a table; I have made 2 queries for the
same data but both give another result. The 2 queries are:
SELECT Samples.Sample,
data_overview.Sample_Name,
data_overview.Sample_Group,
data_overview.NorTum,
data_overview.Sample_Plate,
data_overview.Sentrix_ID,
data_overview.Sentrix_Position,
data_overview.HybNR,
data_overview.Pool_ID
FROM tissue INNER JOIN (
( patient INNER JOIN data_overview
ON patient.Sample = data_overview.Sample)
INNER JOIN Samples ON
(data_overview.Sample_id = Samples.Sample_id) AND
(patient.Sample = Samples.Sample)
) ON
(tissue.Sample_Name = data_overview.Sample_Name) AND
(tissue.Sample_Name = patient.Sample_Name)
WHERE data_overview.Sentrix_ID= 1416198
OR data_overview.Pool_ID='GS0005701-OPA'
OR data_overview.Pool_ID='GS0005702-OPA'
OR data_overview.Pool_ID='GS0005703-OPA'
OR data_overview.Pool_ID='GS0005704-OPA'
OR data_overview.Sentrix_ID= 1280307
ORDER BY Samples.Sample;")
And the other is
SELECT Samples.Sample,
data_overview.Sample_Name,
data_overview.Sample_Group,
data_overview.NorTum,
data_overview.Sample_Plate,
data_overview.Sentrix_ID,
data_overview.Sentrix_Position,
data_overview.HybNR,
data_overview.Pool_ID
FROM tissue INNER JOIN
(
(patient INNER JOIN data_overview
ON patient.Sample = data_overview.Sample)
INNER JOIN Samples ON
(data_overview.Sample_id = Samples.Sample_id)
AND (patient.Sample = Samples.Sample)) ON
(tissue.Sample_Name = data_overview.Sample_Name)
AND (tissue.Sample_Name = patient.Sample_Name)
WHERE ((
(data_overview.Sentrix_ID)=1280307)
AND (
(data_overview.Pool_ID)="GS0005701-OPA"
OR (data_overview.Pool_ID)="GS0005702-OPA"
OR (data_overview.Pool_ID)="GS0005703-OPA"
OR (data_overview.Pool_ID)="GS0005704-OPA"))
OR (((data_overview.Sentrix_ID)=1416198))
ORDER BY data_overview.Sample;
The one in the top is working quite well but it still won't filter the sentrix_ID.
The second 1 is created with Access but when I try to run this Query in R it gave
a unexpected symbol error. So if anyone knows how to create a query that filter POOL_ID and Sentrix_id with the given parameters thanks in advance
Is it a case of making the where clause something like this:
WHERE Sentrix_ID = 1280307 AND (Pool_ID = 'VAL1' OR Pool_ID = 'VAL2' OR Pool_ID = 'VAL3')
i.e. making sure you have brackets around the "OR" components?
Maybe you meant:
...
WHERE data_overview.Sentrix_ID IN (1280307,1416198 )
AND data_overview.Pool_ID IN ("GS0005701-OPA", "GS0005702-OPA", "GS0005703-OPA" ,"GS0005704-OPA")
;