SQL Update sequence data based upon date field - sql-server

I am attempting to update a table that contains deed information. Specifically property ID, sale sequence, and deed date. The program generates the sale sequence data sequentially regardless of the deed date or prior deed information for the property in question.
[property_ID] [sale_number] [sale_deed_date]
1 1 01/15/1990
1 2 06/25/1970
1 3 08/12/1930
What I would like to accomplish is re-sequence sale_number data so they are in chronological order. Similar to this:
[property_ID] [sale_number] [sale_deed_date]
1 1 08/12/1930
1 2 06/25/1970
1 3 01/15/1990
Any help with this would be greatly appreciated.

You can do this by grabbing the correct order in a cte:
;WITH cte AS (SELECT property_ID, sales_number, sales_deed_date, rn = ROW_NUMBER() OVER (PARTITION BY Property_ID ORDER BY sales_deed_date) FROM tablename)
UPDATE t
SET t.sales_number = cte.rn
FROM tablename t
INNER JOIN cte ON t.property_ID = cte.property_ID AND t.sales_deed_date = cte.sales_deed_date

Related

how can i get the latest record in database based on datetime by comparing 2 tables [duplicate]

This question already has answers here:
Retrieving last record in each group from database - SQL Server 2005/2008
(2 answers)
Closed 3 years ago.
I have two tables say one with the code and its corresponding display name and another table with its results and its history.
table 1:
code name
101 provide
102 modify
103 cease
104 cancel
table 2:
code result environment date time
101 Pass test 16/08/2019 06:19:35
102 Pass acc 15/08/2019 06:19:35
101 Pass test 16/08/2019 07:19:35
103 Fail test 14/08/2019 06:19:35
102 Pass test 12/08/2019 10:19:35
104 Pass acc 13/08/2019 20:19:35
I would like to pick the most recent record specific to an environment & code and display as follows,
code name result date time
101 provide Pass 16/08/2019 06:19:35
102 modify Pass 12/08/2019 10:19:35
103 cease Fail 14/08/2019 06:19:35
I am pretty new to MSSQL.
Could you please help.
Thanks in Advance
Following query would give you desired result:
SELECT * FROM
(
SELECT code, name , environment, result , [date], [time]
ROW_NUMBER() OVER (PARTITION BY environment, Code ORDER BY [Date] desc, [Time] desc) rn
FROM table1 t1
LEFT JOIN table2 t2 ON t1.code=t2.code
) AS T
Where T.rn = 1
Your query should be something like this :
WITH cte AS (
SELECT t2.code, t2.name , t2.result , t2.date, t2.time
ROW_NUMBER() (PARTITION BY t2.environment, t2.code ORDER BY date desc, time desc) rn
FROM table1 t1
LEFT JOIN table2 t2 ON t1.code=t2.code
)
SELECT
*
FROM cte
WHERE rn = 1;

How to select date and previous date

I have a table of referral records with a start date and end date. If the person has had previous referrals I need to retrieve the start and end date of the referral previous to the current one.
Any ideas would be greatly appreciated!
Example of what I hope to achieve
Per ID Ref ID Refrl_Start_D Refrl_End_D Prev_Refrl_S Prev_Refrl_S
1 5 10/10/2018 Null 01/02/2018 03/03/2018
2 4 05/04/2018 Null 01/01/2017 01/03/2017
1 3 01/02/2018 03/03/2018 02/01/2017 20/01/2017
1 2 02/01/2018 20/01/2018 Null Null
2 1 01/01/2018 01/03/2018 Null Null
Is have tried adding a Rank calc grouped by person. My plan was to create another table offset it by 1 and join them (i.e. Join referral 5 with 4). However I couldn't figure out how to get the join right.
SELECT DIM_PERSON_ID,
FACT_REFERRAL_ID,
REFRL_START_DTTM,
REFRL_END_DTTM
FROM FACT_REFERRALS;
You can use LAG here
SELECT DIM_PERSON_ID,
FACT_REFERRAL_ID,
REFRL_START_DTTM,
REFRL_END_DTTM
PrevStart = LAG(REFRL_START_DTTM)
OVER(PARTITION BY DIM_PERSON_ID
ORDER BY REFRL_START_DTTM DESC),
PrevEnd = LAG(REFRL_END_DTTM)
OVER(PARTITION BY DIM_PERSON_ID
ORDER BY REFRL_END_DTTMDESC)
FROM FACT_REFERRALS R;
You should be able to construct this with a CTE to calculate a rank/row number for each record based on the referral dates, then join the CTE to itself to get the previous referral. E.g:
WITH RANKED_REFERRALS AS (
SELECT DIM_PERSON_ID,
FACT_REFERRAL_ID,
REFRL_START_DTTM,
REFRL_END_DTTM,
ROW_NUMBER() OVER(PARTITION BY DIM_PERSON_ID ORDER BY REFRL_START_DATE) AS ROWNUM
FROM FACT_REFERRALS
)
SELECT A.DIM_PERSON_ID,
A.ACT_REFERRAL_ID,
A.REFRL_START_DTTM,
A.REFRL_END_DTTM,
B.REFRL_START_DTTM,
B.REFRL_END_DTTM
FROM RANKED_REFERRALS A
LEFT JOIN RANKED_REFERRALS B ON B.DIM_PERSON_ID = A.DIM_PERSON_ID AND B.ROWNUM = A.ROWNUM - 1

unique chat records sql

I have DB which having 5 column as follows:
message_id
user_id_send
user_id_rec
message_date
message_details
Looking for a SQL Serve Query, I want to Filter Results from two columns (user_id_send,user_id_rec)for Given User ID based on following constrains:
Get the Latest Record (filtered on date or message_id)
Only Unique Records (1 - 2 , 2 - 1 are same so only one record will be returned which ever is the latest one)
Ordered by Descending based on message_id
SQL Query
The main purpose of this query is to get records of user_id to find out to whom he has sent messages and from whom he had received messages.
I have also attached the sheet for your reference.
Here is my try
WITH t
AS (SELECT *
FROM messages
WHERE user_id_sender = 1)
SELECT DISTINCT user_id_reciever,
*
FROM t;
WITH h
AS (SELECT *
FROM messages
WHERE user_id_reciever = 1)
SELECT DISTINCT user_id_sender,
*
FROM h;
;WITH tmpMsg AS (
SELECT M2.message_id
,M2.user_id_receiver
,M2.user_id_sender
,M2.message_date
,M2.message_details
,ROW_NUMBER() OVER (PARTITION BY user_id_receiver+user_id_sender ORDER BY message_date DESC) AS 'RowNum'
FROM messages M2
WHERE M2.user_id_receiver = 1
OR M2.user_id_sender = 1
)
SELECT T.message_id
,T.user_id_receiver
,T.user_id_sender
,T.message_date
,T.message_details
FROM tmpMsg T
WHERE RowNum <= 1
The above should fetch you the results you are looking for when you query for a particular user_id (replace the 1 with parameter e.g. #p_user_id). The user_id_receiver+user_id_sender in the PARTITION clause ensure that records with user id combinations such as 1 - 2, 2 - 1 are not selected twice.
Hope this helps.
select * from
(
select ROW_NUMBER() over (order by message_date DESC) as rowno,
* from messages
where user_id_receiver = 1
--order by message_date DESC
) T where T.rowno = 1
UNION ALL
select * from
(
select ROW_NUMBER() over (order by message_date DESC) as rowno,
* from messages
where user_id_sender = 1
-- order by message_date DESC
) T where T.rowno = 1
Explanation: For each group of user_id_sender, it orders internally by message_date desc, and then adds row numbers, and we only want the first one (chronologically last). Then do the same for user_id_receiver, and union the results together to get 1 result set with all the desired rows. You can then add your own order by clause and additional where conditions at the end as required.
Of course, this only works for any 1 user_id at a time (replace =1 with #user_id).
To get a result from all user_id's at once, is a totally different query, so I hope this helps?

showing one record within 48 hours using sql

I am having an issue with my date values and the data types for the date field is date-time but at the sametime i am getting a lot of records for the same id within 48 hours. The goal is just to return one record only if patient makes visit to the hospital within 48. For example if patient A goes to ER on 1/1/2014 and again goes back to 1/2/2014 then i only want to show the first visit which 1/1/2014. I really believe the issue is at this line
AND A.[ADMT_TS] < DateAdd(d, 2, ADMT_TS)
and i think i need to do some conversion first in order to get the correct values.
here is my query and please not that i have other queries before the select statement here but i am only posting this section which where i am trying to get the first 48 hours.
SELECT [ID], [LOCATION], [ADMT_TS]
FROM ERS WHERE RN = 1
UNION ALL
SELECT [ID], [LOCATION], [ADMT_TS]
FROM ERS A
WHERE RN > 1 AND EXISTS (SELECT 1 FROM ERS WHERE RN = 1 AND [ID] = A.[ID])
AND NOT EXISTS(SELECT 1 FROM ERS WHERE RN = 1 AND [ID] = A.[ID] AND A.[ADMT_TS] < DateAdd(d, 2, ADMT_TS))
This will work but may not be the best option. If you post some data and give us an idea of how many rows may/will be in ERS table, I can adjust the query if needed
SELECT [Id]
,[Loc]
,MIN([admt_ts])
FROM [NewJunk].[dbo].[ERS]
WHERE RN = 1
GROUP BY id, loc

T-SQL SELECT DISTINCT & ROW_NUMBER() OVER Ordering Problem

I'm trying to select DISTINCT rows from a view using ROW_NUMBER() OVER for paging. When I switched the ORDER BY field from a SMALLDATETIME to INT I started getting weird results:
SELECT RowId, Title, HitCount FROM
( SELECT DISTINCT Title, HitCount, ROW_NUMBER() OVER(ORDER BY HitCount DESC) AS RowId FROM ou_v_Articles T ) AS Temp
WHERE RowId BETWEEN 1 AND 5
This query returns:
RowId | Title | HitCount
=======================
4 --- 9
1 --- 43
3 --- 11
2 --- 13
5 --- 0
The results are obviously not in the correct order. I'm not sure what the problem is here, but when I removed DISTINCT it orders them correctly.
Thanks.
Applying DISTINCT to a column list containing ROW_NUMBER() will always result in every row being distinct, as there is one ROW_NUMBER per row.
Is the RowId value you're getting correct? Perhaps you just need an ORDER BY RowId clause on the outer query?
Have you tried just using an order by on the outer select and removing the OVER clause?

Resources