SQL - Generate a UniqueIdentifier based on rows value - sql

I want to generate unique ids based on what the value of a certain row is:
I have row1 and I want to generate new unique values based on row. Please see example below:
ROW 1 ROW2
====== =====
A101517 --> 68F66F3A-616B-45AA-B0EE-AC1B01040596
A101517 --> 68F66F3A-616B-45AA-B0EE-AC1B01040596
A233446 --> 56B79D73-0DBC-4EDA-8F8A-A76300C741AB
A233446 --> 56B79D73-0DBC-4EDA-8F8A-A76300C741AB
A233446 --> 56B79D73-0DBC-4EDA-8F8A-A76300C741AB
A110027 --> 3EF0A1B5-B634-4549-9227-AA0F014040A2
Current solution:
UPDATE ROW2 SET ROW2 = NEWID();
THis is generating new values for each record. I want the same newid() when matching row1.

You could do an update join from your table to a CTE which generates single GUID value for each distinct ROW1 value.
WITH cte AS (
SELECT DISTINCT ROW1, NEWID() AS ROW2
FROM yourTable
)
UPDATE t1
SET ROW2 = t2.ROW2
FROM yourTable t1
INNER JOIN cte t2
ON t2.ROW1 = t1.ROW1;

Related

Generating the same random number per column values

I have a table which in which I would like to generate random numbers in a specific format (e.g. TEST-10256). For which I have been using the below:
concat('TEST-' , uniform(10000, 99000, RANDOM()))
However I now want to update a table with these random numbers based on two columns, so the desired outcome would be this:
I am not sure how to keep the same random value per previously matching it on the same values in ROW1 & ROW2.
Based on query from #Lukasz, we can use update statement.
-- Original
select * from test;
ROW1
ROW2
A
12
A
12
B
5
B
5
C
1
C
1
D
10
-- Update statement
update test t set t.row2 = t1.new_col
from (select row1, row2,
CONCAT('TEST-' , uniform(10000, 99000, RANDOM())) new_col
from (select distinct row1, row2 from test)
)t1
where t1.row1 = t.row1
and t1.row2 = t.row2;
-- After update
select * from test;
ROW1
ROW2
A
TEST-37642
A
TEST-37642
B
TEST-39082
B
TEST-39082
C
TEST-50195
C
TEST-50195
D
TEST-14564
Step 1: Generate a temporary table for possible values:
CREATE OR REPLACE TEMPORARY TABLE random_values
AS
SELECT ROW1, ROW2, CONCAT('TEST-' , uniform(10000, 99000, RANDOM())) AS new_value
FROM (SELECT DISTINCT ROW1, ROW2 FROM <table_name>) AS sub;
Step 2: Join using the newly generated and materialized values:
SELECT t.ROW1, rv.new_value AS ROW2
FROM <table_name> t
JOIN random_values rv
ON t.ROW1 = rv.ROW1
AND t.ROW2 = rv.ROW2;
Output:
Try using the MERGE statement to populate your new field. It allows you to fully run your query then apply its results as an UPDATE.
You can get the syntax here

SQL Query: Modify Next Row Based On Current Row

Using SQL Server 2012.
The table I'm working with is shown below, along with code for the query. When I find ReasonString_S = 'Fault Reset' I would like to add that rows DurationMinutes_D to the next row and delete the current row.
I think a case when statement would work but I kept getting syntax issues and I'm fairly new to sql queries.
select ROW_NUMBER() OVER (ORDER BY EntryDate_T) AS Row, e.equip_name,
ReasonString_S, DurationMinutes_D, rt.Name_S ProcStateString, EntryDate_T
into #temptable
from AT_PM_PlantStateEvent pse
inner join EQUIPMENT e on pse.OwnerKey_I = e.equip_key
inner join dbo.AT_PM_ReasonTree rt on pse.ReasonKey_64 = rt.atr_key
where EntryDate_T >= #jobstart and EntryDate_T < #jobend
and rt.Name_S <> 'Running'
and e.equip_name = #mach
Thanks for the help!
It seems Row is your identity column if not then don't hesitate to create or use another existing one. It has many benefits as it's very useful in your case you can perform the desired operation with the help of that simply using JOIN as below:
create table #test(rowNum int identity(1,1),
ReasonString_S varchar(50),
DurationMinutes_D float)
insert into #test values
('Model1',0.34),
('Model2',0.35),
('Model3',0.36)
DATA:
rowNum ReasonString_S DurationMinutes_D
-----------------------------------------
1 Model1 0.34
2 Model2 0.35
3 Model3 0.36
update t set t.ReasonString_S = u.DurationMinutes_D
from #test t
left join #test u on u.rowNum = t.rowNum+1
OUTPUT:
rowNum ReasonString_S DurationMinutes_D
-----------------------------------------
1 0.35 0.34
2 0.36 0.35
3 NULL 0.36
Here's a general answer. To update a row based on the value in the next row, you should use the LEAD function. First you need to identify which column you want to sort by in order to determine which row is the next row. LEAD lets you get the value of a particular column from the next row. If you write a subquery using the LEAD function (which can only appear in the SELECT or ORDER BY clause), you can update by joining to the subquery.
Conversely, to update a row based on the value in the previous row, you'd use the LAG function.
Here's an example:
declare #t1 table (id int, val varchar(10))
insert into #t1 values (1, 'val1')
insert into #t1 values (2, 'val2')
insert into #t1 values (3, 'val3')
update #t1 set val = sq.next_row_val
from #t1 t1
inner join (
select t1.id, LEAD(t1.val) over (order by t1.id) as next_row_val
from #t1 t1
)sq on t1.id = sq.id
select * from #t1
id val
1 val2
2 val3
3 NULL

updating a table by moving data from one row to another multiple times

have an sql table and I need to take row 2 and move data in column 4 & 5 and move it to row 1. The values in column 4 & 5 are dynamic (ie not the same each time)
background on the table. every 8 rows are grouped together (by an action_id ascending) to another entity in another table (but the other table isnt needed for this task)
for example
action_id = 839283 col 4 = space col 5 = space
action_id = 839284 col 4 = SMS col 5 = L1
i need to move the SMS & L1 to the row above and blank out the row where action_id = 839284
this will repeat multiple times.
I was thinking of creating a select into a temp table to get the rows i need to change (using 2 other tables as links) but i caon't work out how to move data from the one row to the other dynamically
Assumptions:
sql server
action_id values are always one apart
3 stpes:
select action_id as To_Empty
into #EmptyMe
from MyTable
where col4 is not null
with CTE as
(
select action_id,
col4,
col5,
lag(col4) over (order by action_id) as n_col4,
lag(col5) over (order by action_id) as n_col5
from MyTable
where col4 is not null
)
update CTE
set col4 = n_col4, col5 = n_col5
update MyTable
set col4 = null, col5 = null
where exists (select 1 from #EmptyMe where action_id = To_Empty)

How to remove duplicate values from a table

I'm working on pulling data to a table which has two data sets of data loaded to temp table and finally inserts into table. There are 2 records which are duplicates but i need both the records if their value on one column is same else delete it. Col1 and col4 are primary keys
col1 col2 col3 col4
--------------------
a ab abc x
a ab abc y
b ab abc y
b ab abc z
what i want is forget about col 2 and col3, check in col1 if row 1 and row 2 are same it should go check col4 and if row1 and row 2 are different it should display both row1 and row 2 even if row 2 and row 3 in col4 are same. so if the records are as i mentioned it should allow all 4 values but with the logic i wrote it is returning row1,row3,row4 because it is considering row2 and row3 of col 1 with row 2 row 3 of col 4 and displaying only 3 records but i want all records. Please help me how to write a logic in sql for this situation.
Based on what I have understood from your question, you could do something like this..
DELETE i
FROM YourTable i INNER JOIN
(
SELECT col1,col4
FROM YourTable
GROUP BY col1,col4
HAVING count(col2)>1
) t ON t.col1 = i.col1 AND t.col4 = i.col4
Live Demo Here
Or if ou want to keep only one record and remove other duplicate records, you could do like this..
;with cte as
(
SELECT *,row_number() over(partition by col1,col4 order by col1,col4) as rn
FROM YourTable
)
DELETE from cte where rn>1
Live Demo Here

sql query to subtract two table values and save them in first table?

How do I subtract one table column value from another table column value, and save the value in the first table column in the process?
Thanks for your help.
Where tablename is the table and col1 is the first column and col2 is the second column.
UPDATE tablename SET col1 = (col2 - col1)
If you are meaning that the values are coming from different tables then the query is much the same:
UPDATE tablename SET col1 = ((SELECT col2 from tablename2) - col1)
It's hard to be sure without details about your tables or how they're related, but you might want something like
UPDATE t1
SET col = t1.col - t2.col
FROM mytable t1
JOIN myothertable t2 ON t2.pkCol = t1.pkCol
Not sure what you are looking for, but pick your example:
update CarBrand
set SortIndex = (select SortIndex from CarBrand where CarBrandId = 3615) + 7
where CarBrandId = 3619
update CarBrand
set SortIndex = SortIndex - OtherColumn
where ...