Select the highest Id Where serviceId occurs more than once - sql

I have inherited a codebase in Web forms and are having trouble with a SQL query.
SELECT foretag.namn, foretag.epost, foretag.forlangEj, service_fakturering.*
FROM foretag
INNER JOIN service ON foretag.id = service.foretagsid
INNER JOIN service_fakturering ON service.id = service_fakturering.service_id
WHERE service_fakturering.giltighets_datum <= DATEADD(D, 30, GETDATE())
ORDER BY bestallnings_datum DESC, id DESC
In the table service_fakturering there are multiple rows with the same service_id
I need to select the last one, max id, to be used in the INNER JOIN service_fakturering ON service.id = service_fakturering.service_id

Using ROW_NUMBER() function, along with common table expression, it can be done like this:
WITH cte_service_fakturering AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY service_id ORDER BY id DESC) RN
FROM service_fakturering
)
SELECT foretag.namn, foretag.epost, foretag.forlangEj, cte.*
FROM foretag
INNER JOIN service ON foretag.id = service.foretagsid
INNER JOIN cte_service_fakturering cte ON service.id = cte.service_id AND cte.RN = 1
WHERE service_fakturering.giltighets_datum <= DATEADD(D, 30, GETDATE())
ORDER BY bestallnings_datum DESC, id DESC

The Sub select will group your service_fakturering rows and get the maxId for you. This is then used to join back into your query and filter for only those rows you are interested in.
SELECT foretag.namn, foretag.epost, foretag.forlangEj, service_fakturering.*
FROM foretag
INNER JOIN service ON foretag.id = service.foretagsid
INNER JOIN service_fakturering ON service.id = service_fakturering.service_id
INNER JOIN (Select service_fakturering.service_id, Max(service_fakturering.id) as Id
FROM service_fakturering
GROUP BY service_fakturering.service_id) x
ON x.service_id = service_fakturering.service_id
AND x.Id = service_fakturering.Id
WHERE service_fakturering.giltighets_datum <= DATEADD(D, 30, GETDATE())
ORDER BY bestallnings_datum DESC, id DESC

Try this...
You could use ROW_NUMBER to denote an order for the set
WITH CTE
AS (
SELECT *
, ROW_NUMBER() OVER (
PARTITION BY service_id ORDER BY ID DESC
) ROWNUM
FROM service_fakturering
)
SELECT foretag.namn
, foretag.epost
, foretag.forlangEj
, service_fakturering.*
FROM foretag
INNER JOIN service
ON foretag.id = service.foretagsid
INNER JOIN service_fakturering
ON service.id = service_fakturering.service_id
AND ROW_NUM = 1
WHERE service_fakturering.giltighets_datum <= DATEADD(D, 30, GETDATE())
ORDER BY bestallnings_datum DESC
, id DESC

Related

Select all records between two dates but one record on same day depending on plate

I have select query :
select
f.FirmaID,f.FirmaAdi,t.BelgeID,t.BelgeTuru,t.Tarih,t2.Plaka,t2.SasiNo,t4.AracMarka,t4.AracTip,case when x.Miktar=1 then 4 else x.miktar end as LastikAdet,
t3.CariKodu,t3.CariAdi,t3.CariGsm1,t3.CariGsm2,t3.CariTel1,t3.CariTel2,t3.CariAdres
from alsatr t WITH (NOLOCK)
left join Firma f WITH (NOLOCK) on f.FirmaID = t.AlsatrFirmaID
left join AracBilgi t2 WITH (NOLOCK) on t2.AracBilgiUID = t.AsAracBilgiUID and t2.AracBilgiID= t.AracBilgi
left join Cari t3 WITH (NOLOCK) on t.AsCariUID= t3.CariUID
left join Araclar t4 WITH (NOLOCK) on t4.AracID= t2.AB_AracID
outer apply
(select COUNT(1) soktak,Miktar FROM alsatD d WITH (NOLOCK)
where
d.AlsatDUID = t.AlsatrUID and d.AsStokKodu='LA-0001' group by Miktar) x
where
isnull(t3.FiloID,0) > 0
and t.Tarih between '04.30.2020' and '04.31.2020'
and t.BelgeTuru=55
and x.soktak > 0
and f.FirmaID not in (1,2,103,106,109,114)
order by t.Tarih desc, f.FirmaID desc, t.BelgeID desc
So I want to select all records between two days but I want to select one,latest record (maybe depends on last BelgeID ) on same day with same plate (plaka).
Enclose your query inside a CTE and use ROW_NUMBER() window function:
WITH cte AS (
<your query here>
)
SELECT
t.FirmaID, t.FirmaAdi, t.BelgeID, t.BelgeTuru, t.Tarih, t.Plaka, t.SasiNo, t.AracMarka,
t.AracTip, t.LastikAdet, t.CariKodu, t.CariAdi, t.CariGsm1, t.CariGsm2, t.CariTel1,
t.CariTel2, t.CariAdres
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY Tarih, Plaka ORDER BY BelgeID DESC) rn
FROM cte
) t
WHERE t.rn = 1

What will be the query for this?

JOIN public.match m ON (s.stadium_id = m.stadium_id)
group
AS (
)
SELECT round_number
,stadium_name
,spectators
FROM (
SELECT round_number
,stadium_name
,spectators
,RANK() OVER (
PARTITION BY round_number ORDER BY spectators DESC
) AS rank1
FROM t1
) AS s1
WHERE rank1 = 1
<br>
Any smaller query than this?
I think you can just use window functions:
select ms.*
from (select m.round_number, s.stadium_name, m.no_spectators,
row_number() over (partition by m.round_number order by m.no_spectators desc) as seqnum
from public.stadium s join
public.match m
on s.stadium_id = m.stadium_id
) ms
where seqnum = 1
order by m.round_number;
I don't see why aggregation would be needed for the inner query.
You can use a subquery to get the max first
select m.round_number, s.stadium_name, MaxSpec
from public.stadium s
JOIN public.match m ON (s.stadium_id = m.stadium_id)
JOIN
(
select m.round_number, MAX(m.no_spectators) as MaxSpec
from public.stadium s
JOIN public.match m ON (s.stadium_id = m.stadium_id)
group by m.round_number
)a on m.no_spectators = a.MaxSpec
Just one more way to skin this cat. Throw your MAX(no_spectators) into a WHERE clause.
SELECT
m.round_number,
s.stadium_name,
m.no_spectators
FROM
PUBLIC.stadium s
JOIN
PUBLIC.match m
ON s.stadium_id = m.stadium_id
WHERE
m.no_spectators = (SELECT MAX(no_spectators) FROM PUBLIC.match);
That should do for an intro class.

show only MAX rows

i have a table which shows me workhours of postoffices, the problem is that sometimes there are duplicates: for example i have saturday showing twice from one postoffice with the same time.
Solution is to show only 1 saturday with MAX(ID), but i can't deal with that and tha think is that i don't have to show id in select.
this is my script
SELECT h.ID,
h.POSTINDEX,
H.LONGNAME_UA,
h.SHORTNAME_UA,
pt.LONGNAME_UA,
h.parent_Id,
WORKCOMMENT,
INTERVALTYPE,
TO_CHAR(TFROM, 'HH24:MI') AS TFROM,
TO_CHAR(TTO, 'HH24:MI'),
WD.NAME_UA,
WD.NAME_EN,
WD.NAME_RU,
WD.SHORTNAME_UA,
pt.isVPZ,
lr.NAME_UA,
lr.CODE
FROM ADDR_PO_WORKSCHEDULE tt
LEFT JOIN ADDR_POSTOFFICE h
ON tt.POSTOFFICE_ID = h.ID
INNER JOIN mdm_lockReason lr
ON lr.id = H.LOCK_REASON
INNER JOIN ADDR_POSTOFFICEtype pt
ON pt.ID = H.POSTOFFICETYPE_ID
INNER JOIN ADDR_PO_WORKDAYS wd
ON wd.ID = tt.dayofweek
where tt.datestop = TO_DATE('9999-12-31','YYYY-MM-DD') AND tt.postoffice_id = 8221
HAVING MAX(tt.ID)
ORDER BY h.postIndex,
h.POSTOFFICETYPE_ID,
dayofweek,
intervaltype,
tFrom,
tto
as you can see there i've add HAVING MAX(tt.ID) but i understand that it is incorrect and don't know how to solve that. help please!
You can use row_number():
with t as (
<your query here with no `having` and with tt.id as tt_id>
)
select t.*
from (select t.*, row_number() over (order by tt_id desc) as seqnum
from t
) t
where seqnum = 1;
If the source of your duplicate rows is coming from the ADDR_PO_WORKSCHEDULE table, then you can just de-dupe it before you use it in the rest of your query:
SELECT
h.ID, h.POSTINDEX, h.LONGNAME_UA, h.SHORTNAME_UA, pt.LONGNAME_UA, h.parent_Id,
WORKCOMMENT, INTERVALTYPE, TO_CHAR(TFROM, 'HH24:MI') AS TFROM, TO_CHAR(TTO, 'HH24:MI'),
WD.NAME_UA, WD.NAME_EN, WD.NAME_RU, WD.SHORTNAME_UA, pt.isVPZ, lr.NAME_UA, lr.CODE
FROM (
SELECT src.*
FROM (
SELECT t.*,
ROW_NUMBER() OVER(
PARTITION BY tt.postoffice_id, tt.dayofweek -- Group by post office / day of week
ORDER BY <order_columns> -- Rank rows within each group
) AS RowNum
FROM ADDR_PO_WORKSCHEDULE t
) src
WHERE RowNum = 1
) tt
LEFT JOIN ADDR_POSTOFFICE h ON tt.POSTOFFICE_ID = h.ID
INNER JOIN mdm_lockReason lr ON lr.id = H.LOCK_REASON
INNER JOIN ADDR_POSTOFFICEtype pt ON pt.ID = H.POSTOFFICETYPE_ID
INNER JOIN ADDR_PO_WORKDAYS wd ON wd.ID = tt.dayofweek
WHERE tt.datestop = TO_DATE('9999-12-31','YYYY-MM-DD')
AND tt.postoffice_id = 8221
ORDER BY h.postIndex, h.POSTOFFICETYPE_ID, dayofweek, intervaltype, tFrom, tto
Just replace with the columns you want to use to decide which of the "duplicate" rows to keep. If the order doesn't matter, just remove the ORDER BY altogether.
Also, you may want to qualify all column references, since you are selecting from multiple tables.
You can use analytical function as following:
Select * from
(Select <your select column list>,
Row_number() over (partition by h.postindex, trunc(tfrom) order by tt.id desc nulls last) as rn
From <from clause>
Where <where clause>
)
Where rn = 1;
group by is not needed.

row number broken when its used with CTE

This is my query the SQL inside CTE works fine and all I want to get first 20 rows for each city name:
WITH taniCte
AS (
SELECT sl.Adi AS [CityName],
mt.ICD10Kodu AS [Tanı],
count(mt.ICD10Kodu) AS sayi,
RowNum = ROW_NUMBER() OVER (
ORDER BY sl.Adi
)
FROM Muayene.Muayene mm WITH (NOLOCK)
INNER JOIN Muayene.Tani mt WITH (NOLOCK) ON mm.ID = mt.MuayeneId
INNER JOIN Ortak.Kurum ok WITH (NOLOCK) ON mm.CreatedKurumKodu = ok.KurumKodu
INNER JOIN Skrs.Il sl WITH (NOLOCK) ON ok.IlKodu = sl.Kodu
GROUP BY sl.Adi,
mt.ICD10Kodu
) --order by [CityName], sayi desc // commentewhen its moved inside cte
SELECT [CityName],
[Tanı],
sayi,
RowNum
FROM taniCte
WHERE RowNum <= 20
ORDER BY [CityName],
sayi DESC
Eventhough main query works fine the query above returns wrong rows..
I couldn't find any solution on internet
If you need 20 rows per city then your row_number OVER clause in cte should be
with taniCte as
(
select sl.Adi as [CityName]
, mt.ICD10Kodu as [Tanı]
, count(mt.ICD10Kodu) as sayi
, RowNum = ROW_NUMBER()OVER(partition By sl.Adi order by count(mt.ICD10Kodu)) -- this change in over clause
from Muayene.Muayene mm with(nolock)
join Muayene.Tani mt with(nolock) on mm.ID = mt.MuayeneId
join Ortak.Kurum ok with(nolock) on mm.CreatedKurumKodu = ok.KurumKodu
join Skrs.Il sl with(nolock) on ok.IlKodu = sl.Kodu
group by sl.Adi, mt.ICD10Kodu
--order by [CityName], sayi desc // commentewhen its moved inside cte
)
select [CityName], [Tanı],sayi, RowNum
from taniCte
where RowNum <= 20
order by [CityName], sayi desc

How do I group by the most recent date?

I have a HISTORY table that has multiple rows for the same record and I am trying to get the latest (closest to today's date) record. I am attempting to group by the closest date but am having a difficult time. Please check out the query below and advise me.
SELECT DISTINCT *
FROM
(SELECT etc.Complaint.Complaint_ID AS Complaint_ID
FROM etc.Complaint) AS Qry1
LEFT JOIN
(SELECT etc.Complaint.Complaint_ID AS Complaint_ID,
o.Action_User AS Resolved_User,
o.Action_Date AS LastActionDate
FROM etc.Complaint
LEFT OUTER JOIN etc.History as o
ON SUBSTRING(Primary_Key,15,LEN(Primary_Key) - 15) = etc.Complaint.Complaint_ID
AND TABLE_NAME = 'Resolution' AND o.Field_Name = 'Resolved_Ind'
AND New_Value = 1) AS Qry2
ON Qry1.Complaint_ID = Qry2.Complaint_ID
ORDER BY Qry1.Complaint_ID, MAX(Qry2.LastActionDate)
does this change help?
SELECT DISTINCT *
FROM
(SELECT etc.Complaint.Complaint_ID AS Complaint_ID FROM etc.Complaint) AS Qry1
LEFT JOIN
(SELECT etc.Complaint.Complaint_ID AS Complaint_ID,
o.Action_User AS Resolved_User,
o.Action_Date AS LastActionDate
FROM etc.Complaint
LEFT OUTER JOIN
(
SELECT SUBSTRING(Primary_Key,15,LEN(Primary_Key) - 15) as hist_Complaint_ID , MAX(Action_Date) as Action_Date
FROM etc.History
WHERE Field_Name = 'Resolved_Ind'
GROUP BY SUBSTRING(Primary_Key,15,LEN(Primary_Key) - 15)
) as o
ON o.hist_Complaint_ID = etc.Complaint.Complaint_ID
AND TABLE_NAME = 'Resolution' AND o.Field_Name = 'Resolved_Ind'
AND New_Value = 1) AS Qry2
ON Qry1.Complaint_ID = Qry2.Complaint_ID
ORDER BY Qry1.Complaint_ID, Qry2.LastActionDate
You can use ROW_NUMBER and a CTE to get it:
WITH cte AS (
SELECT etc.Complaint.Complaint_ID AS Complaint_ID,
o.Action_User AS Resolved_User,
o.Action_Date AS LastActionDate
row_number() over (partition by etc.Complaint.Complaint_ID order by o.Action_Date desc) AS rn
FROM etc.Complaint
LEFT OUTER JOIN etc.History as o
ON SUBSTRING(Primary_Key,15,LEN(Primary_Key) - 15) = etc.Complaint.Complaint_ID
AND TABLE_NAME = 'Resolution' AND o.Field_Name = 'Resolved_Ind'
AND New_Value = 1
)
SELECT * FROM cte
WHERE rn = 1