Getting latest date in SQL query - sql

I am running this query right now:
WITH Result AS (
select distinct
--pump.Product_PN,
--pump.product_name,
mot.Motor_pn,
Mot.Motor_name,
mas.STLAN AS Usage,
po.DATUV as change_date,
mot.[Procurement type],
mot.Plant as plant,
po.IDNRK AS Component_PN,
mak.MAKTG as component_name
FROM dbo.TBLMAST AS mas
INNER JOIN dbo.TBLSTPO AS po
ON mas.STLNR = po.STLNR
INNER JOIN dbo.TBLMAKT AS mak
ON mak.MATNR = po.IDNRK
--INNER JOIN ['Pumps to motor$'] AS pump
--ON pump.[Motor Product Number] = SUBSTRING(mas.MATNR, PATINDEX('%[^0 ]%', mas.MATNR + ' '), LEN(mas.MATNR))
INNER JOIN Grundfos_motors AS mot
ON mot.Motor_PN = SUBSTRING(mas.MATNR, PATINDEX('%[^0 ]%', mas.MATNR + ' '), LEN(mas.MATNR))
where mas.STLAN = '8' and mot.Motor_PN = '78085617' and mak.MAKTG like '%stator%'
)
select motor_pn, motor_name, plant, change_date, Component_PN, Component_name, cast(getdate() as date) as Date_of_Extraction_date
from result
order by change_date DESC;
The result of this query is this:
From this query result, I want to run another query where the change_date is set to the latest. So I only want to retrieve the data for the latest date and rest is excluded. Something like:
Can anyone help?

You should be able to do:
select motor_pn, motor_name, plant, change_date, Component_PN, Component_name,
cast(getdate() as date) as Date_of_Extraction_date
from (select r.*,
row_number() over (partition by motor_pn order by change_date desc) as seqnum
from result r
) r
where seqnum = 1;

Related

Select only observations with a date more recent than the 30/6/2021 (dd/mm/yyyy)

I have the following code:
Select Tbl.Fromdate, Tbl.Por, Tbl.Porname, Tbl.Bmref3
From(
Select
To_Char(P.Fromdate, 'dd-mm-yyyy') As Fromdate, P.Por, P.Porname, W.Bmref3,
, RANK() OVER (PARTITION BY P.Por ORDER BY P.fromdate DESC) AS rank
From Tmsdat.Climandatecomps W
Inner Join Tmsdat.Portfolios P On (W.Porik = P.Porik)
Where 1=1
) Tbl
Where 1=1
And Tbl.Rank = 1
;
However, I wish to select only the observations that have a Fromdate more recent than the June 30, 2021. I tried to add Tbl.Fromdate> '30-06-2021' to the WHERE clause, but I did not receive the desired results.
Do you have any suggestions?
Thank you in advance.
Best regards,
You would put the condition in the inner query:
Select To_Char(P.Fromdate, 'dd-mm-yyyy') As Fromdate, P.Por, P.Porname, W.Bmref3,
RANK() OVER (PARTITION BY P.Por ORDER BY P.fromdate DESC) AS rank
From Tmsdat.Climandatecomps W inner join
Tmsdat.Portfolios P
On (W.Porik = P.Porik)
Where p.FromDate > date '2021-06-30'

calculate time difference of consecutive row dates in SQL

Hello I am trying to calculate the time difference of 2 consecutive rows for Date (either in hours or Days), as attached in the image
Highlighted in Yellow is the result I want which is basically the difference of the date in that row and 1 above.
How can we achieve it in the SQL? Attached is my complex code which has the rest of the fields in it
with cte
as
(
select m.voucher_no, CONVERT(VARCHAR(30),CONVERT(datetime, f.action_Date, 109),100) as action_date,f.col1_Value,f.col3_value,f.col4_value,f.comments,f.distr_user,f.wf_status,f.action_code,f.wf_user_id
from attdetailmap m
LEFT JOIN awftaskfin f ON f.oid = m.oid and f.client ='PC'
where f.action_Date !='' and action_date between '$?datef' and '$?datet'
),
.*select *, ROW_NUMBER() OVER(PARTITION BY action_Date,distr_user,wf_Status,wf_user_id order by action_Date,distr_user,wf_Status,wf_user_id ) as row_no_1 from cte
cte2 as
(
select *, ROW_NUMBER() OVER(PARTITION BY voucher_no,action_Date,distr_user,wf_Status,wf_user_id order by voucher_no ) as row_no_1 from cte
)
select distinct(v.dim_value) as resid,c.voucher_no,CONVERT(datetime, c.action_Date, 109) as action_Date,c.col4_value,c.comments,c.distr_user,v.description,c.wf_status,c.action_code, c.wf_user_id,v1.description as name,r.rel_value as pay_office,r1.rel_value as site
from cte2 c
LEFT OUTER JOIN aagviuserdetail v ON v.user_id = c.distr_user
LEFT OUTER JOIN aagviuserdetail v1 ON v1.user_id = c.wf_user_id
LEFT OUTER JOIN ahsrelvalue r ON r.resource_id = v.dim_Value and r.rel_Attr_id = 'P1' and r.period_to = '209912'
LEFT OUTER JOIN ahsrelvalue r1 ON r1.resource_id = v.dim_Value and r1.rel_Attr_id = 'Z1' and r1.period_to = '209912'
where c.row_no_1 = '1' and r.rel_value like '$?site1' and voucher_no like '$?trans'
order by voucher_no,action_Date
The key idea is lag(). However, date/time functions vary among databases. So, the idea is:
select t.*,
(date - lag(date) over (partition by transaction_no order by date)) as diff
from t;
I should note that this exact syntax might not work in your database -- because - may not even be defined on date/time values. However, lag() is a standard function and should be available.
For instance, in SQL Server, this would look like:
select t.*,
datediff(second, lag(date) over (partition by transaction_no order by date), date) / (24.0 * 60 * 60) as diff_days
from t;

Creating a Month Bucket from Query Result

I have the following query result:
But I want to group the results by number, and categorize the quantity by month, so the resulting output would be:
How can I create a month bucket to pick up the date and make it a column and place the values accordingly. Here is my attempt so far:
select converT(varchar,year(NewShipDate)) + 'M' + MonthBucket,
*
from(
select ItemNumber, des.[Product Family], ItemDescription, des.Country, month(RequestedShipDate) as 'Month', ItemOrderedQuantity
from FS_COLine co
join FS_Item it on co.ItemKey = it.ItemKey
left outer join FIN_PLANCAP_2..ProductDescriptions des on it.ItemNumber collate database_default = des.RICNum
where RequestedShipDate >= convert(datetime, '01/01/2016', 120) and
RequestedShipDate <= convert(datetime, '12/31/2016', 120) and
isNumeric(it.ItemNumber) = 1 and
isNumeric(des.RICNum) = 1
--and it.ItemNumber = 35191305
group by ItemNumber, des.[Product Family], ItemDescription, des.Country, month(RequestedShipDate), ItemOrderedQuantity
order by ItemNumber
)A

Return first result only for each unique result

I am having some trouble with duplicating results in SQL Server 2005. I have previously used the ROW NUMBER function to display my query results, but I cannot get the query below to only display rownum 1:
SELECT *
FROM (SELECT l.insbilleddate, l.pickupdate, l.patientname, l.inscompanyname AS Payor, l.tripid,
l.sales, l.cost, l.sales-l.cost AS Profit, l.profitpct AS 'Profit Pct', u.pUPFName + ' ' +
u.pUPLName AS Dispatcher, ROW_NUMBER() OVER (PARTITION BY l.tripid ORDER BY d.trDispatchDate
ASC) AS rownum
FROM pUsersPrinters u
INNER JOIN TranslationDispatch d
INNER JOIN v_OLAPdataTR l ON d.trTripid = l.tripid ON u.pUP_id = d.trDispatchedBy
GROUP BY l.insbilleddate, l.pickupdate, l.patientname, l.inscompanyname, l.tripid, l.sales,
l.cost, l.profitpct, u.pUPFName, u.pUPLName, d.trDispatchDate
HAVING l.insbilleddate >= '6/1/2014' And l.insbilleddate < '7/1/2014' AND l.cost > '0' AND
l.profitpct < '30') q1
WHERE rownum = 1
ORDER BY q1.profitpct
The TranslationDispatch table adds a line each time a user dispatches a trip. If a trip needs to be reassigned the database does not overwrite the original dispatcher, instead it adds another line with the userID, tripID, and dispatch date. The d.trTripid = l.tripid comparison causes the trip to show for each dispatcher that marks it.
As an example, results show as:
TripID trDispatchedBy trDispatchDate
1234 Carlos 6/25/2014 10:00
1234 Tim 6/25/2014 10:02
...but I only want to display Carlos, as he dispatched the trip first.
EDIT: I've adjusted the query above with the help of #Vulcronos to make it work, by adding a table alias (q1) and making the rownum = '1' into rownum = 1 to correctly display my final result.
I would try:
ROW_NUMBER () OVER ( PARTITION BY l.insbilleddate, l.pickupdate, l.patientname,
l.inscompanyname, l.tripid, l.sales, l.cost, l.profitpct, u.pUPFName, u.pUPLName,
d.trDispatchDate ORDER BY trDispatchDate ASC)
This should give you a row number of one on every groups earliest dispatch date. Then you can wrap your whole query in:
select *
from (my_query)
where rownum = 1
How about adding "TOP 1" to the outside query
SELECT TOP 1 *
FROM(SELECT L.Insbilleddate,
L.Pickupdate,
L.Patientname,
L.Inscompanyname AS Payor,
L.Tripid,
L.Sales,
L.Cost,
L.Sales - L.Cost AS Profit,
L.Profitpct AS 'Profit Pct',
U.Pupfname + ' ' + U.Puplname AS Dispatcher,
ROW_NUMBER()OVER(PARTITION BY L.Tripid ORDER BY D.Trdispatchdate ASC)AS Rownum
FROM Pusersprinters U
INNER JOIN Translationdispatch D
INNER JOIN V_Olapdatatr L ON D.Trtripid = L.Tripid ON U.Pup_Id = D.Trdispatchedby
GROUP BY L.Insbilleddate,
L.Pickupdate,
L.Patientname,
L.Inscompanyname,
L.Tripid,
L.Sales,
L.Cost,
L.Profitpct,
U.Pupfname,
U.Puplname,
D.Trdispatchdate
HAVING L.Insbilleddate >= '6/1/2014'
AND L.Insbilleddate < '7/1/2014'
AND L.Cost > '0'
AND L.Profitpct < '30') A
ORDER BY A.Profitpct;

SQL - Replace repeated rows with null values while preserving number of rows

I am trying to get only one instance of a year instead of 12 because I am using this column in a lookup table to provide parameters to a report. Because I am using both monthly and yearly data, I am trying to get them both in the same table.
I have a table like this
--Date--------Year
--------------------
1/2012-------2012
2/2012-------2012
3/2012-------2012
4/2012-------2012
5/2012-------2012
6/2012-------2012
7/2012-------2012
8/2012-------2012
9/2012-------2012
10/2012------2012
11/2012------2012
12/2012------2012
1/2013-------2013
2/2013-------2013
And this is my desired table
--Date--------Year
--------------------
1/2012-------2012
2/2012-------null
3/2012-------null
4/2012-------null
5/2012-------null
6/2012-------null
7/2012-------null
8/2012-------null
9/2012-------null
10/2012------null
11/2012------null
12/2012------null
1/2013-------2013
2/2013-------null
Can someone give me an idea of how to solve a problem like this?
The code I am using right now is
SELECT CAST(MONTH(rmp.EcoDate) AS Varchar(2)) + '/' + CAST(YEAR(rmp.EcoDate) AS varchar(4)) AS Date, Year(rmp.EcoDate) as EcoYear
FROM PhdRpt.ReportCaseList_542 AS rcl INNER JOIN
CaseCases AS cc ON rcl.CaseCaseId = cc.CaseCaseId INNER JOIN
PhdRpt.RptMonthlyProduction_542 AS rmp ON rcl.ReportRunCaseId = rmp.ReportRunCaseId`
GROUP BY rmp.EcoDate
You can do this by enumerating the rows within a year. Then update all but the first:
with toupdate as (
select t.*, row_number() over (partition by [year] order by [date]) as seqnum
from t
)
update toupdate
set [year] = NULL
where seqnum > 1;
If you want this as a select statement:
with ts as (
select t.*, row_number() over (partition by [year] order by [date]) as seqnum
from t
)
select [date],
(case when seqnum = 1 then [year] end) as [year]
from ts;