How do I remove duplicate results by looking for max date? - sql

I know I have duplicate results from this query because the tables ReleaseHistory and IterationHistory have multiple records per ReleaseID and IterationID. I would like to only select the records with max date from dbo.ReleaseHistory and dbo.IterationHistory. How would I do that in this query? SQL SERVER 2008
SELECT dbo.Assignable.AssignableID AS ID,
dbo.EntityType.Abbreviation AS Entity,
dbo.General.Name, dbo.Assignable.Effort,
dbo.Assignable.EffortCompleted,
dbo.Assignable.EffortToDo,
dbo.EntityState.Name AS State,
dbo.ReleaseHistory.Name AS Release,
dbo.IterationHistory.Name AS Iteration,
dbo.General.CustomField3 AS [Scrum Team]
FROM dbo.Assignable INNER JOIN
dbo.General ON dbo.Assignable.AssignableID =
dbo.General.GeneralID INNER JOIN
dbo.EntityType ON dbo.General.EntityTypeID =
dbo.EntityType.EntityTypeID INNER JOIN
dbo.EntityState ON dbo.Assignable.EntityStateID =
dbo.EntityState.EntityStateID AND
dbo.EntityType.EntityTypeID =
dbo.EntityState.EntityTypeID INNER JOIN
dbo.ReleaseHistory ON dbo.Assignable.ReleaseID =
dbo.ReleaseHistory.ReleaseID INNER JOIN
dbo.IterationHistory ON
dbo.Assignable.IterationID =
dbo.IterationHistory.IterationID LEFT OUTER JOIN
dbo.CustomField ON dbo.General.CustomField3 =
dbo.CustomField.CustomFieldID
WHERE (dbo.Assignable.ProjectID = 4054)
GROUP BY dbo.Assignable.AssignableID,
dbo.EntityType.Abbreviation,
dbo.General.Name,
dbo.Assignable.Effort,
dbo.Assignable.EffortCompleted,
dbo.Assignable.EffortToDo,
dbo.EntityState.Name,
dbo.ReleaseHistory.Name,
dbo.IterationHistory.Name,
dbo.General.CustomField3

Brian,
I am amusing you are doing this in MS SQL and there will always be at least one record in ReleaseHistory and IterationHistory tables. If assumptions are correct then you can simply use CROSS APPLY to get top 1 record from both tables.
SELECT
dbo.Assignable.AssignableID AS ID ,
dbo.EntityType.Abbreviation AS Entity ,
dbo.General.Name ,
dbo.Assignable.Effort ,
dbo.Assignable.EffortCompleted ,
dbo.Assignable.EffortToDo ,
dbo.EntityState.Name AS State ,
Release ,
Iteration ,
dbo.General.CustomField3 AS [Scrum Team]
FROM
dbo.Assignable
INNER JOIN dbo.General ON dbo.Assignable.AssignableID = dbo.General.GeneralID
INNER JOIN dbo.EntityType ON dbo.General.EntityTypeID = dbo.EntityType.EntityTypeID
INNER JOIN dbo.EntityState ON dbo.Assignable.EntityStateID = dbo.EntityState.EntityStateID
AND dbo.EntityType.EntityTypeID = dbo.EntityState.EntityTypeID
CROSS APPLY( SELECT TOP 1 name Release FROM ReleaseHistory WHERE ReleaseID = Assignable.ReleaseID ORDER BY MaxDateColumn) a
CROSS APPLY( SELECT TOP 1 name Iteration FROM IterationHistory WHERE IterationID = Assignable.IterationID ORDER BY MaxDateColumn) b
LEFT OUTER JOIN dbo.CustomField ON dbo.General.CustomField3 = dbo.CustomField.CustomFieldID
WHERE
( dbo.Assignable.ProjectID = 4054 )
GROUP BY
dbo.Assignable.AssignableID ,
dbo.EntityType.Abbreviation ,
dbo.General.Name ,
dbo.Assignable.Effort ,
dbo.Assignable.EffortCompleted ,
dbo.Assignable.EffortToDo ,
dbo.EntityState.Name ,
dbo.ReleaseHistory.Name ,
dbo.IterationHistory.Name ,
dbo.General.CustomField3

Related

SQL Server aggregate function without group by

I want to include tcon.Inductive_Injection_Hours, tcon.Capacitive_Injection_Hours without applying group by. How can I do that?
SELECT
bp.Serial_Number,
tcon.Serial_Number AS ConverterSerialNumber,
MAX(tcon.Time_Stamp) AS DateStamp,
tcon.Inductive_Injection_Hours,
tcon.Capacitive_Injection_Hours
FROM
dbo.Bypass AS bp
INNER JOIN
dbo.Converter AS c ON bp.Bypass_ID = c.Bypass_ID
INNER JOIN
dbo.Converter_Tel_Data AS tcon ON c.Converter_ID = tcon.Converter_ID
WHERE
(bp.Site_ID = 7)
GROUP BY
bp.Serial_Number, tcon.Serial_Number,
tcon.Inductive_Injection_Hours, tcon.Capacitive_Injection_Hours
ORDER BY
ConverterSerialNumber
I have figured it out.
select [data].Serial_Number,Time_Stamp,Inductive_Injection_Hours,Capacitive_Injection_Hours,b.Serial_Number from Converter_Tel_Data as [data]
inner join dbo.Converter AS c On [data].Converter_ID = c.Converter_ID
inner join dbo.Bypass as b on c.Bypass_ID = b.Bypass_ID
WHERE
(Time_Stamp = (SELECT MAX(Time_Stamp) FROM Converter_Tel_Data WHERE Converter_ID = [data].Converter_ID)) And ([data].Site_ID=7)
ORDER BY [data].Serial_Number
You can use row_number - either in a CTE/derived table or using a trick with TOP 1.
Select Top 1 With Ties
bp.Serial_Number
, tcon.Serial_Number AS ConverterSerialNumber
, tcon.Time_Stamp AS DateStamp
, tcon.Inductive_Injection_Hours
, tcon.Capacitive_Injection_Hours
From dbo.Bypass AS bp
Inner Join dbo.Converter AS c On bp.Bypass_ID = c.Bypass_ID
Inner Join dbo.Converter_Tel_Data AS tcon ON c.Converter_ID = tcon.Converter_ID
Where bp.Site_ID = 7
Order By
row_number() over(Partition By bp.Serial_Number Order By tcon.Time_Stamp desc)
This should return the latest row from the tconn table for each bp.Serial_Number.

Which query is faster to execute

Following are two options to query CTE and NFSE data. Pls advise !
A similar approach may have to be used in many places.
I would like you to verify them and suggest, if there are better options.
Option 1: Query CTE with all necessary joins UNION with query on NFSe with all necessary joins
SELECT DISTINCT 'CTE' as docTypeID
, cte.isqn_mstr_cd as ctePk
, cte.ct_e_cd
, cter.stat_desc
, awb.CREATE_DT
, awb.AWB_NBR
, awb.SHPR_NM
, awbs.DEST_LOC_CD
, nfe.NT_FSCL_CD
, nfe.FSCL_DOC_NBR
FROM cte_identity_master cte
INNER JOIN cte_response_detail cter ON (cte.isqn_mstr_cd = cter.isqn_mstr_cd)
LEFT JOIN match_ref_awb mawb ON (cte.isqn_ref_cd = mawb.isqn_mstr_cd)
LEFT JOIN awb_cust_master awb ON (mawb.awb_nbr = awb.awb_nbr)
LEFT JOIN awb_shipment_detail awbs ON (awb.awb_nbr = awbs.awb_nbr)
LEFT JOIN match_ref_nfe mnfe ON (cte.isqn_ref_cd = mnfe.isqn_mstr_cd)
LEFT JOIN nfe_identity_master nfe ON (mnfe.nt_fscl_cd = nfe.nt_fscl_cd)
UNION
SELECT DISTINCT 'NFSE' as docTypeID
, nfse.isqn_mstr_cd as nfsePk
, nfse.rp_s_id
, nfser.stat_desc
, awb.CREATE_DT
, awb.AWB_NBR
, awb.SHPR_NM
, awbs.DEST_LOC_CD
, nfe.NT_FSCL_CD
, nfe.FSCL_DOC_NBR
FROM nfse_request_detail nfse
INNER JOIN nfse_response_detail nfser ON (nfse.isqn_mstr_cd = nfser.isqn_mstr_cd)
LEFT JOIN match_ref_awb mawb ON (nfse.isqn_ref_cd = mawb.isqn_mstr_cd)
LEFT JOIN awb_cust_master awb ON (mawb.awb_nbr = awb.awb_nbr)
LEFT JOIN awb_shipment_detail awbs ON (awb.awb_nbr = awbs.awb_nbr)
LEFT JOIN match_ref_nfe mnfe ON (nfse.isqn_ref_cd = mnfe.isqn_mstr_cd)
LEFT JOIN nfe_identity_master nfe ON (mnfe.nt_fscl_cd = nfe.nt_fscl_cd)
;
Option 2: Use Union of CTe and NFSe first and then apply joins with other tables
SELECT ctnf.*
, awb.CREATE_DT
, awb.AWB_NBR
, awb.SHPR_NM
, awbs.DEST_LOC_CD
, nfe.NT_FSCL_CD
, nfe.FSCL_DOC_NBR
FROM (
SELECT DISTINCT 'CTE' as docTypeID
, cte.isqn_mstr_cd as docPk
, cte.ct_e_cd as docNbr
, cter.stat_desc as docStat
, cte.isqn_ref_cd as matchRef
FROM cte_identity_master cte
INNER JOIN cte_response_detail cter ON (cte.isqn_mstr_cd = cter.isqn_mstr_cd)
UNION
SELECT DISTINCT 'NFSE' as docTypeID
, nfse.isqn_mstr_cd as nfsePk
, nfse.rp_s_id
, nfser.stat_desc
, nfse.isqn_ref_cd
FROM nfse_request_detail nfse
INNER JOIN nfse_response_detail nfser ON (nfse.isqn_mstr_cd = nfser.isqn_mstr_cd)
) ctnf
LEFT JOIN match_ref_awb mawb ON (ctnf.matchRef = mawb.isqn_mstr_cd)
LEFT JOIN awb_cust_master awb ON (mawb.awb_nbr = awb.awb_nbr)
LEFT JOIN awb_shipment_detail awbs ON (awb.awb_nbr = awbs.awb_nbr)
LEFT JOIN match_ref_nfe mnfe ON (ctnf.matchRef = mnfe.isqn_mstr_cd)
LEFT JOIN nfe_identity_master nfe ON (mnfe.nt_fscl_cd = nfe.nt_fscl_cd)
;
Both approaches of the above will have following Where Clause:
WHERE lower(cte.sttn_cd) = lower(:stationId)
and (:documentType is null or lower(:documentType) = 'cte')
and (:shipperName is null or lower(awb.shipperNm) like lower(concat(concat('%',:shipperName),'%')))
and (:awbCreated is null or to_char(awb.createDt, 'MM-DD-YYYY') = :awbCreated)
and (:awbNumber is null or m2.awbNbr like concat(concat('%',:awbNumber),'%'))
and (:serviceType = 0 or awbs.baseServiceCd = :serviceType)
and (:commitmentDate is null or awbs.commitmentDate = :commitmentDate)
and (:ursa is null or lower(awbs.ursaCd) like lower(concat(concat('%',:ursa),'%')))
and (:destLocationId is null or lower(awbs.destLocCd) like lower(concat(concat('%',:destLocationId),'%')))
and (:nfeNumber is null or nfe.fiscalDocumentNumber like concat(concat('%',:nfeNumber),'%'))
PLEASE SUGGEST - Output of these two approaches to get data which one will be better to fix at Java End to retrieve the data.
Any help will be greatly appreciated. Also suggest if there is any other better query apart from these two!

Two select statements turn into one

I have set of two queries. In first query, if is separate from second, I got good results.
First query
SELECT *
FROM
(
SELECT nks.[Id]
, nks.[IdNarudzbe]
, nks.[IdArtikla] as artikal
, nks.[IdUsluge]
, nks.[Naziv]
, nks.Kolicina
, p.Naziv as kupac
, p.Id as kupacId
, p.Adresa
, p.Telefon
, nkz.[BrojDokumenta] AS nalog
, nkz.[BrojDokumentaKroz] AS nalogKroz
, nkz.[RokIsporuke]
, nkz.[IdNastaloOdDokumenta]
, d.Naziv as drzava
FROM [dbo].[NarudzbaKupacaStavke] nks
LEFT JOIN [dbo].[NarudzbeKupacaZaglavlje] nkz
ON nkz.Id = nks.IdNarudzbe
LEFT JOIN dbo.Partneri p
ON nkz.IdKupac = p.Id
LEFT JOIN dbo.Drzave d
ON p.IdDrzava = d.Id
WHERE idArtikla IN ('FP80PUR-08', 'FP80PUR-09', 'FP80PUR-12')
AND nkz.[VrstaDokumenta] = 'PRO'
AND nkz.StatusArhive = 0
--...
from first query nkz.[IdNastaloOdDokumenta] is important to second
SELECT BrojDokumenta
, BrojDokumentaKroz
FROM .[dbo].[NarudzbeKupacaZaglavlje]
where id = nkz.[IdNastaloOdDokumenta]
For ex. In first query I got nkz.[IdNastaloOdDokumenta] = 20. Number 20 I use in second query in where statement, and value I get from BrojDokumenta, I would like to join to first query.
I was wondering if is possible to make one query out of these two. I think I can not union operator because number of column from these two queries don't match.
The same table, and the same columns are already in the first query. Perhaps you want a self-join, like this:
FROM [dbo].[NarudzbaKupacaStavke] nks
LEFT JOIN [dbo].[NarudzbeKupacaZaglavlje] nkz
ON nkz.Id = nks.IdNarudzbe
LEFT JOIN [dbo].[NarudzbeKupacaZaglavlje] nkz2
ON nkz2.Id = nkz.[IdNastaloOdDokumenta]
LEFT JOIN dbo.Partneri p
ON nkz.IdKupac = p.Id
LEFT JOIN dbo.Drzave d
ON p.IdDrzava = d.Id
WHERE idArtikla IN ('FP80PUR-08', 'FP80PUR-09', 'FP80PUR-12')
AND nkz.[VrstaDokumenta] = 'PRO'
AND nkz.StatusArhive = 0

Need to select ONLY if visiting one location

In the following SQL, it was looking at only those vouchers from location_ID = 5. How can I code that, I ONLY want from a Patient_ID who ONLY visited location_ID 5?
SELECT "Vouchers"."Patient_ID", "vwGenPatInfo"."Patient_Number",
"Practitioners"."Practitioner_ID", "Practitioners"."First_Name",
"Practitioners"."Last_Name", "vwGenPatInfo"."Patient_First_Name",
"vwGenPatInfo"."Patient_Last_Name", "vwGenPatInfo"."Patient_DOB",
"vwGenPatInfo"."Patient_Sex", "Vouchers"."Carrier_ID",
"Vouchers"."Billing_Date", "Vouchers"."Patient_Policy_ID",
"Vouchers"."Location_ID"
FROM ("Ntier_70751"."PM"."vwGenPatInfo" "vwGenPatInfo"
INNER JOIN "Ntier_70751"."PM"."Vouchers" "Vouchers"
ON "vwGenPatInfo"."Account_ID"="Vouchers"."Account_ID")
INNER JOIN "Ntier_70751"."PM"."Practitioners" "Practitioners"
ON "Vouchers"."Actual_Prov_Practitioner_ID"="Practitioners"."Practitioner_ID"
--
WHERE "Vouchers"."Location_ID"=5
Here is one way to do this. I also got rid of all those unneeded double quotes and used proper aliases.
SELECT V.Patient_ID
, gpi.Patient_Number
, P.Practitioner_ID
, P.First_Name
, P.Last_Name
, gpi.Patient_First_Name
, gpi.Patient_Last_Name
, gpi.Patient_DOB
, gpi.Patient_Sex
, V.Carrier_ID
, V.Billing_Date
, V.Patient_Policy_ID
, V.Location_ID
FROM Ntier_70751.PM.vwGenPatInfo gpi
INNER JOIN Ntier_70751.PM.Vouchers V ON gpi.Account_ID = V.Account_ID
INNER JOIN Ntier_70751.PM.Practitioners P ON V.Actual_Prov_Practitioner_ID = P.Practitioner_ID
cross apply
(
select V2.Account_ID
from Ntier_70751.PM.Vouchers V2
where V2.Account_ID = V.Account_ID
group by V2.Account_ID
HAVING MAX(Location_ID) = 5
AND MIN(Location_ID) = 5
) x
Put a condition as say;
WHERE "Vouchers"."Location_ID" = 5
I would go with not exists
SELECT "Vouchers"."Patient_ID", "vwGenPatInfo"."Patient_Number",
"Practitioners"."Practitioner_ID", "Practitioners"."First_Name", "Practitioners"."Last_Name", "vwGenPatInfo"."Patient_First_Name", "vwGenPatInfo"."Patient_Last_Name", "vwGenPatInfo"."Patient_DOB", "vwGenPatInfo"."Patient_Sex", "Vouchers"."Carrier_ID", "Vouchers"."Billing_Date", "Vouchers"."Patient_Policy_ID", "Vouchers"."Location_ID"
FROM "Ntier_70751"."PM"."vwGenPatInfo" "vwGenPatInfo" INNER JOIN
"Ntier_70751"."PM"."Vouchers" "Vouchers"
ON "vwGenPatInfo"."Account_ID" = "Vouchers"."Account_ID" INNER JOIN
"Ntier_70751"."PM"."Practitioners" "Practitioners"
ON "Vouchers"."Actual_Prov_Practitioner_ID" = "Practitioners"."Practitioner_ID"
WHERE "Vouchers"."Location_ID"=5
and not exists (select 1
FROM "Ntier_70751"."PM"."Vouchers" "Vouchers2"
WHERE "Vouchers2"."Patient_ID" = "Vouchers2"."Patient_ID"
AND "Vouchers2"."Location_ID"<>5)
Just using the condition 'WHERE "Vouchers"."Location_ID" = 5'will return all Patient_IDs that visited the that location at least once but not exclusively. There are several ways to do it but the cleanest would be using having max (location_id) <5 and min (location_id) >5

SQL INNER JOIN DISTINCT with max function

I have the tables tbMeasurement and tbPatientMeasurement .
tbMeasurement
MeasurementIDP
MeasurementName
tbPatientMeasurement
PatientMeasurementIDP
MeasurementIDF
MeasurementValue
Taken (Datetime)
When doing the following query:
SELECT DISTINCT dbo.tbMeasurement.MeasurementName
, dbo.tbPatientMeasurement.MeasurementValue
, dbo.tbPatientMeasurement.Taken
FROM dbo.tbMeasurement
INNER JOIN dbo.tbPatientMeasurement
ON dbo.tbMeasurement.MeasurementIDP = dbo.tbPatientMeasurement.MeasurementIDF
This returns a double entry of one of the MeasurementName.
and i also want MeasurementName,MeasurementValue by max Taken(datetime).
Try this one -
SELECT DISTINCT
m.MeasurementName
, p2.MeasurementValue
, p2.Taken
FROM dbo.tbMeasurement m
JOIN (
SELECT
p.MeasurementValue
, Taken = MAX(p.Taken)
FROM dbo.tbPatientMeasurement p
GROUP BY m.MeasurementName, p.MeasurementValue
) p2 ON m.MeasurementIDP = p2.MeasurementIDF
SELECT
m.MeasurementName
, p.MeasurementValue
, a.Taken
FROM dbo.tbMeasurement m
INNER JOIN dbo.tbPatientMeasurement p ON m.MeasurementIDP = p.MeasurementIDF
INNER JOIN
(
select MeasurementIDF,MAX(Taken) as taken
from tbPatientMeasurement
group by MeasurementIDF
) a on a.MeasurementIDF=p.MeasurementIDF and a.taken=p.Taken