I have 4 dates (derived from separate subqueries) as in below but I want to find the MAX and MIN dates of the values returned.
I've tried using CASE which will not work with the null values.
Also tried using COALESCE in the subs to get values and then using CTE but this also didn't work.
(The overall query is to find customers with no -9 in a1.id)
There's a lot of help in SO but nothing that I can get to fit this purpose.
Any help would be greatly appreciated.
DESIRED COLUMNS
PAT_ID Date1 Date2 Date3 Date4 MAX MIN
1 01/04/2015 25/12/2000 02/02/2011 01/04/2015 25/12/2000
2 05/08/1950 11/11/2011 11/11/2011 05/08/1950
3 04/01/1958 04/01/1958 04/01/1958
4 01/01/1900 01/01/1900
5 15/08/2017 07/07/1967 15/08/2017 07/07/1967
select distinct
ca1.id AS PT_ID,
(select Top 1 s1z.appointmen ApptDate
from schl_booking_appoin s1z
LEFT OUTER JOIN core_patient c3z ON s1z.patient = c3z.id
LEFT OUTER JOIN schl_appt_history_s s2z ON s1z.currentsta = s2z.id
LEFT OUTER JOIN applookup_instance a2z ON s2z.lkp_status = a2z.id
where (c3z.id = ca1.id and a2z.text not like '%cancelled%' and s1z.appointmen
> :SYS_DATE_TIME)
order by s1z.appointmen asc ) AS Date1,
(select Top 1
s1q.appointmen ApptDate
from schl_booking_appoin s1q
LEFT OUTER JOIN core_patient c3q ON s1q.patient = c3q.id
LEFT OUTER JOIN schl_appt_history_s s2q ON s1q.currentsta = s2q.id
LEFT OUTER JOIN applookup_instance a2q ON s2q.lkp_status = a2q.id
where (c3q.id = ca1.id and a2q.text not like '%cancelled%' and s1q.appointmen
< :SYS_DATE_TIME)
order by s1q.appointmen desc ) AS Date2,
(select top 1
CONVERT (VARCHAR(20),c2y.admissiond, 103) AdmissionDate
from core_admissiondetai c2y
LEFT OUTER JOIN core_pas_event c3y ON c2y.pasevent = c3y.id
LEFT OUTER JOIN core_patient c4y ON c3y.patient = c4y.id
where (c4y.id = ca1.id)
order by c2y.admissiond desc ) AS Date3,
(select top 1
CONVERT(VARCHAR(20),c5k.arrivaldat,103) ArrivalDate
from core_emergencyatten c5k
LEFT OUTER JOIN core_patient c6k ON c5k.patient = c6k.id
where (c6k.id = ca1.id)
order by c5k.arrivaldat desc ) AS Date4
from core_patient ca1
LEFT OUTER JOIN core_patient_c_identifi ca2 ON ca1.id = ca2.id
LEFT OUTER JOIN applookup_instance aa2 ON ca1.lkp_sex = aa2.id
LEFT OUTER JOIN applookup_instance aa1 ON ca2.lkp_c_ty = aa1.id
LEFT OUTER JOIN applookup_instance ab1 ON ca1.lkp_overseascl = ab1.id
LEFT OUTER JOIN core_organisation cx4 ON ca1.practice = cx4.id
WHERE ca1.id IN
(
select c1.id core_patient_c1_id
from core_patient c1
LEFT OUTER JOIN core_patient_c_identifi c2 ON c1.id = c2.id
LEFT OUTER JOIN applookup_instance a1 ON c2.lkp_c_ty = a1.id
where ((ca2.merged = 0 or ca2.merged is null)
and aa1.id = -2404) )
AND ca1.id NOT IN (
select c1.id core_patient_c1_id
from core_patient c1
LEFT OUTER JOIN core_patient_c_identifi c2 ON c1.id = c2.id
LEFT OUTER JOIN applookup_instance a1 ON c2.lkp_c_ty = a1.id
where (c1.namesurname not like '%XXTEST%'
and c1.namesurname not like '%ZZ%'
and a1.id = -9)
)
try this version. Your old query acts as a subquery and introducing a new column definition to get the Max Date.
SELECT PT_ID,
(
SELECT Max(v)
FROM (VALUES (Date1), (Date2), (Date3),(Date4)) AS value(v)
) as [MaxDate]
FROM
(
select distinct
ca1.id AS PT_ID,
(select Top 1 s1z.appointmen ApptDate
from schl_booking_appoin s1z
LEFT OUTER JOIN core_patient c3z ON s1z.patient = c3z.id
LEFT OUTER JOIN schl_appt_history_s s2z ON s1z.currentsta = s2z.id
LEFT OUTER JOIN applookup_instance a2z ON s2z.lkp_status = a2z.id
where (c3z.id = ca1.id and a2z.text not like '%cancelled%' and s1z.appointmen
> :SYS_DATE_TIME)
order by s1z.appointmen asc ) AS Date1,
(select Top 1
s1q.appointmen ApptDate
from schl_booking_appoin s1q
LEFT OUTER JOIN core_patient c3q ON s1q.patient = c3q.id
LEFT OUTER JOIN schl_appt_history_s s2q ON s1q.currentsta = s2q.id
LEFT OUTER JOIN applookup_instance a2q ON s2q.lkp_status = a2q.id
where (c3q.id = ca1.id and a2q.text not like '%cancelled%' and s1q.appointmen
< :SYS_DATE_TIME)
order by s1q.appointmen desc ) AS Date2,
(select top 1
CONVERT (VARCHAR(20),c2y.admissiond, 103) AdmissionDate
from core_admissiondetai c2y
LEFT OUTER JOIN core_pas_event c3y ON c2y.pasevent = c3y.id
LEFT OUTER JOIN core_patient c4y ON c3y.patient = c4y.id
where (c4y.id = ca1.id)
order by c2y.admissiond desc ) AS Date3,
(select top 1
CONVERT(VARCHAR(20),c5k.arrivaldat,103) ArrivalDate
from core_emergencyatten c5k
LEFT OUTER JOIN core_patient c6k ON c5k.patient = c6k.id
where (c6k.id = ca1.id)
order by c5k.arrivaldat desc ) AS Date4
from core_patient ca1
LEFT OUTER JOIN core_patient_c_identifi ca2 ON ca1.id = ca2.id
LEFT OUTER JOIN applookup_instance aa2 ON ca1.lkp_sex = aa2.id
LEFT OUTER JOIN applookup_instance aa1 ON ca2.lkp_c_ty = aa1.id
LEFT OUTER JOIN applookup_instance ab1 ON ca1.lkp_overseascl = ab1.id
LEFT OUTER JOIN core_organisation cx4 ON ca1.practice = cx4.id
WHERE ca1.id IN
(
select c1.id core_patient_c1_id
from core_patient c1
LEFT OUTER JOIN core_patient_c_identifi c2 ON c1.id = c2.id
LEFT OUTER JOIN applookup_instance a1 ON c2.lkp_c_ty = a1.id
where ((ca2.merged = 0 or ca2.merged is null)
and aa1.id = -2404) )
AND ca1.id NOT IN (
select c1.id core_patient_c1_id
from core_patient c1
LEFT OUTER JOIN core_patient_c_identifi c2 ON c1.id = c2.id
LEFT OUTER JOIN applookup_instance a1 ON c2.lkp_c_ty = a1.id
where (c1.namesurname not like '%XXTEST%'
and c1.namesurname not like '%ZZ%'
and a1.id = -9)
)
)Sub
You could do the following:
make your query into a CTE;
flatten the data so it becomes a list of PT_IDs and dates;
from this flattened data find the maximum and minimum date per PT_ID;
bring this all back together in one final query.
This is a stab at doing all of the above:
WITH x AS (
select distinct
ca1.id AS PT_ID,
(select Top 1 s1z.appointmen ApptDate
from schl_booking_appoin s1z
LEFT OUTER JOIN core_patient c3z ON s1z.patient = c3z.id
LEFT OUTER JOIN schl_appt_history_s s2z ON s1z.currentsta = s2z.id
LEFT OUTER JOIN applookup_instance a2z ON s2z.lkp_status = a2z.id
where (c3z.id = ca1.id and a2z.text not like '%cancelled%' and s1z.appointmen
> :SYS_DATE_TIME)
order by s1z.appointmen asc ) AS Date1,
(select Top 1
s1q.appointmen ApptDate
from schl_booking_appoin s1q
LEFT OUTER JOIN core_patient c3q ON s1q.patient = c3q.id
LEFT OUTER JOIN schl_appt_history_s s2q ON s1q.currentsta = s2q.id
LEFT OUTER JOIN applookup_instance a2q ON s2q.lkp_status = a2q.id
where (c3q.id = ca1.id and a2q.text not like '%cancelled%' and s1q.appointmen
< :SYS_DATE_TIME)
order by s1q.appointmen desc ) AS Date2,
(select top 1
CONVERT (VARCHAR(20),c2y.admissiond, 103) AdmissionDate
from core_admissiondetai c2y
LEFT OUTER JOIN core_pas_event c3y ON c2y.pasevent = c3y.id
LEFT OUTER JOIN core_patient c4y ON c3y.patient = c4y.id
where (c4y.id = ca1.id)
order by c2y.admissiond desc ) AS Date3,
(select top 1
CONVERT(VARCHAR(20),c5k.arrivaldat,103) ArrivalDate
from core_emergencyatten c5k
LEFT OUTER JOIN core_patient c6k ON c5k.patient = c6k.id
where (c6k.id = ca1.id)
order by c5k.arrivaldat desc ) AS Date4
from core_patient ca1
LEFT OUTER JOIN core_patient_c_identifi ca2 ON ca1.id = ca2.id
LEFT OUTER JOIN applookup_instance aa2 ON ca1.lkp_sex = aa2.id
LEFT OUTER JOIN applookup_instance aa1 ON ca2.lkp_c_ty = aa1.id
LEFT OUTER JOIN applookup_instance ab1 ON ca1.lkp_overseascl = ab1.id
LEFT OUTER JOIN core_organisation cx4 ON ca1.practice = cx4.id
WHERE ca1.id IN
(
select c1.id core_patient_c1_id
from core_patient c1
LEFT OUTER JOIN core_patient_c_identifi c2 ON c1.id = c2.id
LEFT OUTER JOIN applookup_instance a1 ON c2.lkp_c_ty = a1.id
where ((ca2.merged = 0 or ca2.merged is null)
and aa1.id = -2404) )
AND ca1.id NOT IN (
select c1.id core_patient_c1_id
from core_patient c1
LEFT OUTER JOIN core_patient_c_identifi c2 ON c1.id = c2.id
LEFT OUTER JOIN applookup_instance a1 ON c2.lkp_c_ty = a1.id
where (c1.namesurname not like '%XXTEST%'
and c1.namesurname not like '%ZZ%'
and a1.id = -9)
)),
y AS (
SELECT PT_ID, Date1 AS [Date] FROM x WHERE Date1 IS NOT NULL
UNION ALL
SELECT PT_ID, Date2 AS [Date] FROM x WHERE Date2 IS NOT NULL
UNION ALL
SELECT PT_ID, Date3 AS [Date] FROM x WHERE Date3 IS NOT NULL
UNION ALL
SELECT PT_ID, Date4 AS [Date] FROM x WHERE Date4 IS NOT NULL),
z AS (
SELECT
PT_ID,
MIN([Date]) AS Min_Date,
MAX([Date]) AS Max_Date
FROM
y
GROUP BY
PT_ID)
SELECT
x.PT_ID,
x.Date1,
x.Date2,
x.Date3,
x.Date4,
z.Min_Date,
z.Max_Date
FROM
x
LEFT JOIN z ON z.PT_ID = x.PT_ID;
Related
I've this query below, my need is that I want to do the substraction between 2 columns: S and M&L.
The problem is that S and M&L are a subqueries ... I've tried to store those subqueries on a variable, but it's not working ...
SELECT
[STORE] = ET2.ET_LIBELLE ,
[SELLER] = GCL5.GCL_LIBELLE,
(SELECT
COUNT(DISTINCT GL_NUMERO)
FROM GCLIGNEARTDIM
LEFT OUTER JOIN ETABLISS ET4 ON GL_ETABLISSEMENT=ET4.ET_ETABLISSEMENT
LEFT OUTER JOIN COMMERCIAL GCL4 ON GL_REPRESENTANT=GCL4.GCL_COMMERCIAL
WHERE
AND ET4.ET_LIBELLE = ET2.ET_LIBELLE
AND GCL4.GCL_LIBELLE = GCL5.GCL_LIBELLE
AND GP_TOTALTTC < 200
) S,
(SELECT
COUNT(DISTINCT GL_NUMERO)
FROM GCLIGNEARTDIM
LEFT OUTER JOIN ETABLISS ET4 ON GL_ETABLISSEMENT=ET4.ET_ETABLISSEMENT
LEFT OUTER JOIN COMMERCIAL GCL4 ON GL_REPRESENTANT=GCL4.GCL_COMMERCIAL
WHERE
AND ET4.ET_LIBELLE = ET2.ET_LIBELLE
AND GCL4.GCL_LIBELLE = GCL5.GCL_LIBELLE
AND GP_TOTALTTC > 200
) 'M&L'
FROM GCLIGNEARTDIM
LEFT OUTER JOIN ETABLISS ET2 ON GL_ETABLISSEMENT=ET2.ET_ETABLISSEMENT
LEFT OUTER JOIN COMMERCIAL GCL5 ON GL_REPRESENTANT=GCL5.GCL_COMMERCIAL
WHERE
GL_DATEPIECE = '2019-02-28'
GROUP BY
ET2.ET_LIBELLE,
GCL5.GCL_LIBELLE
If you're using Microsoft SQL, then one way to do this would be to use a CTE. I don't have any test data, so I'm just reposting your query (there are issues with the WHERE clauses that need to be addressed):
WITH cteData AS
(
SELECT [STORE] = ET2.ET_LIBELLE
, [SELLER] = GCL5.GCL_LIBELLE
, (
SELECT COUNT(DISTINCT GL_NUMERO)
FROM GCLIGNEARTDIM
LEFT OUTER JOIN ETABLISS ET4 ON GL_ETABLISSEMENT=ET4.ET_ETABLISSEMENT
LEFT OUTER JOIN COMMERCIAL GCL4 ON GL_REPRESENTANT=GCL4.GCL_COMMERCIAL
WHERE ET4.ET_LIBELLE = ET2.ET_LIBELLE
AND GCL4.GCL_LIBELLE = GCL5.GCL_LIBELLE
AND GP_TOTALTTC < 200
) S
, (
SELECT COUNT(DISTINCT GL_NUMERO)
FROM GCLIGNEARTDIM
LEFT OUTER JOIN ETABLISS ET4 ON GL_ETABLISSEMENT=ET4.ET_ETABLISSEMENT
LEFT OUTER JOIN COMMERCIAL GCL4 ON GL_REPRESENTANT=GCL4.GCL_COMMERCIAL
WHERE ET4.ET_LIBELLE = ET2.ET_LIBELLE
AND GCL4.GCL_LIBELLE = GCL5.GCL_LIBELLE
AND GP_TOTALTTC > 200
) 'M&L'
FROM GCLIGNEARTDIM
LEFT OUTER JOIN ETABLISS ET2 ON GL_ETABLISSEMENT=ET2.ET_ETABLISSEMENT
LEFT OUTER JOIN COMMERCIAL GCL5 ON GL_REPRESENTANT=GCL5.GCL_COMMERCIAL
WHERE GL_DATEPIECE = '2019-02-28'
GROUP BY ET2.ET_LIBELLE, GCL5.GCL_LIBELLE
)
SELECT *
, ([S] - [M&L]) AS [S minus M&L]
FROM cteData
**The below query is working badly, and I'm planning to replace case stmt in where clause with temp table. Pls suggest to me some option to rewrite this query
Is there a way to simplify this into multiple SQLs
Also explain me how this case stmt works in where clause**
select DISTINCT
ph.order_type_cd,
c.order_num,
ph.created_date,
os.order_status_desc,
ph.facility_name,
PH.vendor_order_num,
l.lic_nm,
(u.last_nm + ', ' + u.first_nm )as requestor_nm,
bl.billing_location_desc,
ph.ship_to_name,
dm.dispatch_method_name_desc as courier,
PH.po_last_updated_dt as last_updated_date,
(u1.last_nm + ', ' + u1.first_nm )as last_updated_by,
ph.right_grp_id,
c.line_id,
a.material_product_id,
a.parent_material_product_id
from avt_po_detail c
inner join avt_po_hdr ph on ph.order_num = c.order_num
left outer join avt_material_product AS a on a.material_product_id=c.material_product_id
INNER JOIN #entity_ids po on po.entity_id = c.order_num --or #select_pos = 0 )
LEFT OUTER JOIN dbo.ert_product AS pc ON pc.product_id = a.product_id
left outer join ert_product_type as pt on pt.product_type_cd = pc.product_type_cd
LEFT OUTER JOIN dbo.ert_product_xref as xref on xref.product_id = a.parent_product_id AND xref.version_id = 1
left outer join avt_order_status AS OS ON OS.order_status_cd = PH.order_status_cd
left outer join avt_licensee l on l.lic_id = ph.lic_id
left outer join avt_po_from pf on pf.material_product_id = a.material_product_id and pf.line_id = c.line_id
left outer join avt_po_audio_detail pad on pad.line_id = c.line_id
left outer join avt_materials_trans_material MTM on mtm.sequence_no = c.video_seq_no
left outer join avt_user u on u.userid = ph.requestor_id
left outer join avt_user u1 on u1.userid = ph.po_last_updated_by
left outer join avt_billing_location bl on bl.billing_location_cd = PH.billing_location_cd
left outer join avt_dispatch_method_name dm on dm.dispatch_method_name_id = PH.dispatch_method_name_id
left outer join avt_right_group arg on arg.right_grp_id = ph.right_grp_id
left outer join #prod product on product.product_id=a.product_id and (product.version_id=c.dist_version_id OR product.version_id = 1)
where (pf.from_desc in ( select from_desc from #from_desc ) or #select_form = 0)
and (case WHEN c.dist_version_id IS NULL THEN c.UCS_prod_no
ELSE
CASE
WHEN isnull(pt.version_control_ind, 'N') = 'Y' THEN xref.rss_prod_no
WHEN
isnull(pt.version_control_ind, 'N') = 'N' AND
xref.rss_prod_no IS NULL AND
xref.rss_film_id IS NULL THEN xref.rss_titleid
WHEN
isnull(pt.version_control_ind, 'N') = 'N' AND
xref.rss_prod_no IS NOT NULL AND
xref.rss_film_id IS NULL THEN substring(pc.glacct, 24, 5) -- ASR 3290687
WHEN isnull(pt.version_control_ind, 'N') = 'N' AND xref.rss_film_id IS NOT NULL THEN isnull(substring(pc.glacct, 24, 5), -- ASR 3290687
(
SELECT substring(dbo.ert_product.glacct, 24, 5) -- ASR 3290687
FROM dbo.ert_product
WHERE dbo.ert_product.product_id = a.parent_product_id
))
END
END in (select prod_no from #prod_no) or #prod_no = 0)
I have the below query that returns all diagnosis that do not have a '-829' value associated to them. The query does work but I think that I've made it harder than it should be. Is there a tidier way of doing this?
select distinct
c2.diagnosisn DiagnosisName,
a2.text CareLookup
from core_patdiagnosis c1
LEFT OUTER JOIN core_diagnosis c2 ON c1.diagnosis = c2.id
LEFT OUTER JOIN core_carecontext c3 ON c1.carecontex = c3.id
LEFT OUTER JOIN applookup_instance a1 ON c1.lkp_specialty = a1.id
LEFT OUTER JOIN core_diagnosis_taxonomyma c5 ON c2.id = c5.id
LEFT OUTER JOIN applookup_instance a3 ON c5.lkp_taxonomyna = a3.id
LEFT OUTER JOIN applookup_instance a2 ON c3.lkp_context = a2.id
where c2.id IN
(
select c11.id core_diagnosis_c1_id
from core_diagnosis c11
LEFT OUTER JOIN core_diagnosis_taxonomyma c21 ON c11.id = c21.id
LEFT OUTER JOIN applookup_instance a11 ON c21.lkp_taxonomyna = a11.id
WHERE
c11.isactive = 1
and a11.id != -829 or a11.id is null
)
AND
c2.id NOT IN
(
select c12.id ProcID
from core_procedure c12
LEFT OUTER JOIN core_procedure_taxonomyma c22 ON c12.id = c22.id
LEFT OUTER JOIN applookup_instance a12 ON c22.lkp_taxonomyna = a12.id
WHERE
c12.isactive = 1
and a12.id = -829 or a12.id is null
)
AND
c1.sys_creation_datetime > '01 Dec 2017 00:00:00' AND a2.text like
'%Emergency%'
extra stuff not used
a2.text like '%Emergency%' breaks the outer join
select distinct c2.diagnosisn DiagnosisName, a2.text CareLookup
from core_patdiagnosis c1
JOIN core_diagnosis c2 ON c2.id = c1.diagnosis
JOIN core_carecontext c3 ON c3.id = c1.carecontex
JOIN applookup_instance a2 ON a2.id = c3.lkp_context
where c2.id IN
( select c11.id
from core_diagnosis c11
LEFT OUTER JOIN core_diagnosis_taxonomyma c21 ON c11.id = c21.id
LEFT OUTER JOIN applookup_instance a11 ON c21.lkp_taxonomyna = a11.id
WHERE c11.isactive = 1 and a11.id != -829
or a11.id is null
)
AND
c2.id NOT IN
( select c12.id
from core_procedure c12
LEFT OUTER JOIN core_procedure_taxonomyma c22 ON c12.id = c22.id
LEFT OUTER JOIN applookup_instance a12 ON c22.lkp_taxonomyna = a12.id
WHERE c12.isactive = 1 and a12.id = -829
or a12.id is null
)
AND c1.sys_creation_datetime > '01 Dec 2017 00:00:00'
AND a2.text like '%Emergency%'
You could use a CTE (Common Table Expression - see msdn page):
WITH BufferTableCTE (id)
AS
(...)
SELECT ...
FROM ...
WHERE id in (SELECT id FROM BufferTableCTE WHERE id != -829)
AND NOT id in (SELECT id FROM BufferTableCTE WHERE id = -829)
AND ...
Another way would be to store an intermediate result in a temporary table and then use this temporary table later on (twice, once with id != -829 and once with id = 829)
Both ways would reduce your repeated sql declarations.
Why I get converting error when I use top clause in my query but when I use select * in my query everything is ok.
I use SQL server 2000
I use a view that is created from below code
select sum(g.qty) as qty,g.PartCode,g.PartName,g.arz,g.t,g.OrdNo,max(g.id) as id,g.Val from
(SELECT sum(iv.FinalQty) AS qty, p.PartCode, p.PartName, CAST(RIGHT(p.PartCode, 4) AS float) AS arz,case when isnumeric(LEFT(RIGHT(p.PartCode, 7), 3))=1 then CAST(LEFT(RIGHT(p.PartCode, 7), 3) AS float) / 100 else CAST(LEFT(RIGHT(p.PartCode, 7), 4) AS float)/100 end AS t, ord.OrdNo,
id.id,ctrl.val
FROM INV.InvVchHdr AS hv WITH (nolock) INNER JOIN
INV.InvVchItm AS iv WITH (nolock) ON hv.VchHdrID = iv.VchHdrRef INNER JOIN
inv.Part p WITH (nolock) ON p.Serial = iv.PartRef INNER JOIN
INV.InvRqstItm AS i WITH (nolock) ON i.RqstItmID = iv.RefNum INNER JOIN
INV.InvRqstHdr AS h WITH (nolock) ON h.RqstHdrID = i.HdrRef INNER JOIN
PRD.PrdOrdPlan AS po WITH (nolock) ON po.OrdPlnId = h.OrdPlnBase INNER JOIN
PRD.PrdOrdItem AS oi WITH (nolock) ON oi.OrdItmId = po.OrdItmRef INNER JOIN
PRD.PrdOrder AS ord WITH (nolock) ON ord.OrdID = oi.OrderRef JOIN
inv.InvVchItmCtrl ctrl WITH (nolock) ON ctrl.VchItmRef = iv.VchItmID
join USR.idgen_coil_trace id WITH (nolock) on id.vchitmid=iv.VchItmID
WHERE (hv.VchType = 51) AND (iv.BaseVchType <> 0) and iv.VchItmID>981336159
and isnumeric(LEFT(RIGHT(p.PartCode, 7), 3))=1
AND hv.VchHdrID IN
(SELECT max(i.vchhdrref)
FROM inv.InvVchItm i WITH (nolock) JOIN
inv.InvVchItmCtrl c WITH (nolock) ON c.VchItmRef = i.VchItmID
WHERE i.VchType = 51
GROUP BY i.PartRef, c.Val)
GROUP BY p.PartCode, p.PartName, CAST(RIGHT(p.PartCode, 4) AS float)
, CAST(LEFT(RIGHT(p.PartCode, 7), 3) AS float) / 100
, ord.OrdNo, ctrl.Val,id.id) g
--join USR.idgen_coil_trace id on id.vchitmid=g.VchItmID
group by g.PartCode, g.PartName, g.arz
, g.t, g.OrdNo, g.Val
UNION
select sum(g.qty),g.PartCode,g.PartName,g.SizeW,g.SizeH,g.OrdNo,max(g.id),g.Val from(SELECT sum(iv.FinalQty) AS qty, p.PartCode, p.PartName, cp.SizeW, cp.Sizeh, ord.OrdNo,id.id, ctrl.val
FROM INV.InvVchHdr AS hv WITH (nolock) INNER JOIN
INV.InvVchItm AS iv WITH (nolock) ON hv.VchHdrID = iv.VchHdrRef INNER JOIN
INV.Part AS p WITH (nolock) ON p.Serial = iv.PartRef INNER JOIN
INV.InvRqstItm AS i WITH (nolock) ON i.RqstItmID = iv.RefNum INNER JOIN
INV.InvRqstHdr AS h WITH (nolock) ON h.RqstHdrID = i.HdrRef INNER JOIN
PRD.PrdOrdPlan AS po WITH (nolock) ON po.OrdPlnId = h.OrdPlnBase INNER JOIN
PRD.PrdOrdItem AS oi WITH (nolock) ON oi.OrdItmId = po.OrdItmRef INNER JOIN
PRD.PrdOrder AS ord WITH (nolock) ON ord.OrdID = oi.OrderRef JOIN
inv.InvVchItmCtrl ctrl WITH (nolock) ON ctrl.VchItmRef = iv.VchItmID JOIN
inv.PartCmplmnt cp WITH (nolock) ON cp.PartRef = p.Serial
join USR.idgen_coil_trace id WITH (nolock) on id.vchitmid=iv.VchItmID
WHERE (hv.VchType = 57) AND (iv.BaseVchType <> 0) and iv.VchItmID>981336159
AND PO.PartRef IN (SELECT SERIAL FROM INV.Part P WHERE P.PartName LIKE '%لاف%')
GROUP BY p.PartCode, p.PartName, cp.SizeW, cp.Sizeh, ord.OrdNo,id.id, ctrl.Val)g
--join USR.idgen_coil_trace id on id.vchitmid=g.VchItmID
group by g.PartCode, g.PartName, g.SizeW
, g.SizeH, g.OrdNo, g.Val
UNION
--SELECT *FROM usr.aghili WITH (nolock)
--UNION
--SELECT *
--FROM usr.moradi WITH (nolock)
SELECT qty, PartCode, PartName, arz, t, OrdNo, id, val FROM USR.COIL_TRACE_BAK WITH (nolock)
union
select qty,PartCode,PartName,arz,t,OrdNo,id,Val from usr.unregister_coil_trace WITH (nolock)
this query is correct > select * from usr.coil_trace
this query is not correct > select top 100 * from usr.coil_trace
Top clause should work in sql server 2000.
Though I do not have sql 2000 with me but this link should help you.
Also have a look at answers at this stackover flow link
SELECT
ROW_NUMBER() OVER (PARTITION BY s.ExitStateTypeId ORDER BY s.InsertDate) AS Number
,x.Id
,p.FirstName
,p.LastName
,p.PN
,t.Name
,s.ExitStateTypeId as [Status]
,g.Name
,x.OrganisationId
,d.Name AS Direction
,d.Id AS DirectionId
,h.Name AS Referal
,h.Id AS HealthOrgTypeId
,s.IssueDate
,s.InsertDate
FROM [DB1].[dbo].[Exits] x
INNER JOIN [DB1].[dbo].[ExitStates] s on x.Id = s.ExitId
INNER JOIN [DB1].[dbo].[HealthOrgTypes] h on x.HealthOrgTypeId = h.Id
INNER JOIN [DB1].[dbo].[Directions] d on x.DirectionId = d.Id
INNER JOIN [DB1].[dbo].[HealthCards] c on x.HealthCardId = c.Id
INNER JOIN [DB2].[pr].[TABLE] p on p.Id = c.TABLEId
INNER JOIN [DB3].[orgs].[Organizations] g on g.Id = x.OrganisationId
INNER JOIN [DB4].[dbo].ExitStateTypes t on t.Id = s.ExitStateTypeId
WHERE s.Id = (SELECT MAX(es.Id) from ExitStates es WHERE es.ExitId=x.Id)
ORDER BY s.InsertDate
This is my query, but what I need is that I want only those rows to be enumerated by ROW_NUMBER which s.ExitStateTypeId is in (4,7), for the other rows it should be -1.
Here's the incorrect query just for getting the idea.
SELECT
ROW_NUMBER() OVER (PARTITION BY s.ExitStateTypeId Where s.ExitStateTypeId IN (4,7)
ORDER BY s.InsertDate) AS Number
,x.Id
,p.FirstName
,p.LastName
,p.PN
,t.Name
,s.ExitStateTypeId as [Status]
,g.Name
,x.OrganisationId
,d.Name AS Direction
,d.Id AS DirectionId
,h.Name AS Referal
,h.Id AS HealthOrgTypeId
,s.IssueDate
,s.InsertDate
FROM [DB1].[dbo].[Exits] x
INNER JOIN [DB1].[dbo].[ExitStates] s on x.Id = s.ExitId
INNER JOIN [DB1].[dbo].[HealthOrgTypes] h on x.HealthOrgTypeId = h.Id
INNER JOIN [DB1].[dbo].[Directions] d on x.DirectionId = d.Id
INNER JOIN [DB1].[dbo].[HealthCards] c on x.HealthCardId = c.Id
INNER JOIN [DB2].[pr].[TABLE] p on p.Id = c.TABLEId
INNER JOIN [DB3].[orgs].[Organizations] g on g.Id = x.OrganisationId
INNER JOIN [DB4].[dbo].ExitStateTypes t on t.Id = s.ExitStateTypeId
WHERE s.Id = (SELECT MAX(es.Id) from ExitStates es WHERE es.ExitId=x.Id)
ORDER BY s.InsertDate
So, I want partition by s.ExitStateTypeId just when it is 4 or 7 and -1 for the others
This is data I expect
Perhaps with a combination of CASE and ROW_NUMBER:
SELECT Number = CASE WHEN s.ExitStateTypeId NOT IN (4,7) THEN -1
ELSE Row_number() OVER (
partition BY s.exitstatetypeid
ORDER BY s.insertdate) END,
x.id,
p.firstname,
p.lastname,
p.pn,
t.name,
s.exitstatetypeid AS [Status],
g.name,
x.organisationid,
d.name AS Direction,
d.id AS DirectionId,
h.name AS Referal,
h.id AS HealthOrgTypeId,
s.issuedate,
s.insertdate
FROM [DB1].[dbo].[exits] x
INNER JOIN [DB1].[dbo].[exitstates] s
ON x.id = s.exitid
INNER JOIN [DB1].[dbo].[healthorgtypes] h
ON x.healthorgtypeid = h.id
INNER JOIN [DB1].[dbo].[directions] d
ON x.directionid = d.id
INNER JOIN [DB1].[dbo].[healthcards] c
ON x.healthcardid = c.id
INNER JOIN [DB2].[pr].[table] p
ON p.id = c.tableid
INNER JOIN [DB3].[orgs].[organizations] g
ON g.id = x.organisationid
INNER JOIN [DB4].[dbo].exitstatetypes t
ON t.id = s.exitstatetypeid
WHERE s.id = (SELECT Max(es.id)
FROM exitstates es
WHERE es.exitid = x.id)
ORDER BY s.insertdate
Get row numbers, left outer join and set null row number value to -1 (like below, might have to fix it up a bit as I don't have a schema to work with):
;with RowNumber( ExitId, RowNumber )
as
(
SELECT
x.Id
, ROW_NUMBER() OVER (PARTITION BY s.ExitStateTypeId ORDER BY s.InsertDate)
FROM
[DB1].[dbo].[Exits] x
INNER JOIN [DB1].[dbo].[ExitStates] s
on x.Id = s.ExitId
WHERE
s.Id = (SELECT MAX(es.Id) from ExitStates es WHERE es.ExitId=x.Id)
and s.ExitStateTypeId in ( 4, 7 )
)
SELECT
ISNULL( rn.RowNumber, -1 ) AS Number
,x.Id
,p.FirstName
,p.LastName
,p.PN
,t.Name
,s.ExitStateTypeId as [Status]
,g.Name
,x.OrganisationId
,d.Name AS Direction
,d.Id AS DirectionId
,h.Name AS Referal
,h.Id AS HealthOrgTypeId
,s.IssueDate
,s.InsertDate
FROM [DB1].[dbo].[Exits] x
INNER JOIN [DB1].[dbo].[ExitStates] s on x.Id = s.ExitId
INNER JOIN [DB1].[dbo].[HealthOrgTypes] h on x.HealthOrgTypeId = h.Id
INNER JOIN [DB1].[dbo].[Directions] d on x.DirectionId = d.Id
INNER JOIN [DB1].[dbo].[HealthCards] c on x.HealthCardId = c.Id
INNER JOIN [DB2].[pr].[TABLE] p on p.Id = c.TABLEId
INNER JOIN [DB3].[orgs].[Organizations] g on g.Id = x.OrganisationId
INNER JOIN [DB4].[dbo].ExitStateTypes t on t.Id = s.ExitStateTypeId
left outer join RowNumber rn
on x.Id = rn.ExitId
WHERE s.Id = (SELECT MAX(es.Id) from ExitStates es WHERE es.ExitId=x.Id)
ORDER BY s.InsertDate