Complex INSERT INTO SELECT statement in SQL - sql

I have two tables in SQL. I need to add rows from one table to another. The table to which I add rows looks like:
timestamp, deviceID, value
2020-10-04, 1, 0
2020-10-04, 2, 0
2020-10-07, 1, 1
2020-10-08, 2, 1
But I have to add a row to this table if a state for a particular deviceID was changed in comparison to the last timestamp.
For example this record "2020-10-09, 2, 1" won't be added because the value wasn't changed for deviceID = 2 and last timestamp = "2020-10-08". In the same time record "2020-10-09, 1, 0" will be added, because the value for deviceID = 1 was changed to 0.
I have a problem with writing a query for this logic. I have written something like this:
insert into output
select *
from values
where value != (
select value
from output
where timestamp = (select max(timestamp) from output) and output.deviceID = values.deviceID)
Of course it doesn't work because of the last part of the query "and output.deviceID = values.deviceID".
Actually the problem is that I don't know how to take the value from "output" table where deviceID is the same as in the row that I try to insert.

I would use order by and something to limit to one row:
insert into output
select *
from values
where value <> (select o2.value
from output o2
where o2.deviceId = v.deviceId
order by o2.timestamp desc
fetch first 1 row only
);
The above is standard SQL. Specific databases may have other ways to express this, such as limit or top (1).

Related

Why I Can't show only row who has max value in Sql Server?

This is my query :
WITH TABLE as (
SELECT distinct STJH.[META_CODE_ORIGINE] AS Salle_TMD_JOUR_HISTORIQUE_ID
,STJH.[STJH_DATE_ACTION]
,STJH.[STJH_TYPE_ACTION]
, STH.ST_ID,
STJH.[STJ_JOUR]
,STJH.[STJ_HEURE_DEBUT]
,STJH.[STJ_HEURE_FIN]
,STH.[META_CODE_ORIGINE] AS SALLE_TMD_HISTORIQUE_ID
,STH.[ST_DATE_DEBUT]
,STH.[ST_DATE_FIN]
,STH.[STH_DATE_ACTION]
,MAX (sth.STH_DATE_ACTION) over (partition by STH.[META_CODE_ORIGINE]) as max_date_action,
FROM [BI_EASILY].[bloc].[D_TMD_JOUR_HISTORIQUE] STJH
left JOIN [BI_EASILY].[bloc].[D_TMD_HISTORIQUE] STH ON STJH.[ST_ID] = STH.[ST_ID]
WHERE STJH.[STJH_TYPE_ACTION] <> 3
AND STJH.ST_ID = 37 and STJH.ST_ID = 37
AND STJ_JOUR = 1 )
select * from table where table.max_date_action <= stjh_date_action
This is my result ( sorry i didn't copy manualy a lot of data)
I want to show only last row whose has max value of STJH_Date_Action. When i will remove my filter « Where STJ_JOUR =1 (Monday). I want to show only one row having STJ_JOUR_VALUE = 1. I tried to do this by this condition « where max_date_action< = STJH_DATE_ACTION » but it doesn’t work. Can you help me please.
for all the records in the result (max_date_action<=stjh_date_action) as you partition the data by (STH.[META_CODE_ORIGINE])

SQL: Using case to change column value on 1 row only where value exists on 2 rows

I have a dataset that looks like so:
You'll notice that the Text column has two rows with the same value; PERCENT ACHIEVED. I want to change the Text value on row 2, to PERCENT ACHIEVED MONTH and keep row 5 as-is.
Using a case statement changes both rows. How do I change the value of just one row using SQL only?
I am using SQL Server 2016.
Current SQL to generate the dataset, looks like so
SELECT
DimCompany.SID as CompanyFK,
DimBrand.SID as BrandFK,
DimSalesman.SID as SalesmanFK,
FLD01A as [Text],
FLD024 as [Value]
FROM OPENQUERY(SYSTEM21,'
select
*
from CWAUL.SA080VMF
')
LEFT JOIN DimCompany ON DimCompany.CompanyCode = 'CW'
LEFT JOIN DimBrand ON DimBrand.BrandName = 'Group'
LEFT JOIN DimSalesman ON DimSalesman.SalesmanCode = 'R11'

SQL Statement to select row where previous row status = 'C' AS400

This is being run on sql for IBMI Series 7
I have a table which stores info about orders. Each row has an order number (ON), part number(PN), and sequence number(SEQ). Each ON will have multiple PN's linked to them and each part number has multiple SEQ Number. Each sequence number represents the order in which to do work on the part. Somewhere else in the system once the part is at a location and ready to be worked on it shows a flag. What I want to do is get a list of orders for a location that have not yet arrived but have been closed out on the previous location( Which means the part is on it's way).
I have a query listed below that I believe should work but I get the following error: "The column qualifier or table t undefined". Where is my issue at?
Select * From (SELECT M2ON as Order__Number , M2SEQ as Sequence__Number,
M2PN as Product__Number,ML2OQ as Order__Quantity
FROM M2P
WHERE M2pN in (select R1PN FROM R1P WHERE (RTWC = '7411') AND (R1SEQ = M2SEQ)
)
AND M2ON IN (SELECT M1ON FROM M1P WHERE ML1RCF = '')
ORDER BY ML2OSM ASC) as T
WHERE
T.Order__Number in (Select t3.m2on from (SELECT *
FROM(Select * from m2p
where m2on = t.Order__Number and m2pn = t.Product__Number
order by m2seq asc fetch first 2 rows only
)as t1 order by m2seq asc fetch first row only
) as t3 where t3.m2stat = 'C')
EDIT- Answer for anyone else with this issue
Clutton's Answer worked with slight modification so thank you to him for the fast response! I had to name my outer table and specify that in the subquery otherwise the as400 would kick back and tell me it couldn't find the columns. I also had to order by the sequence number descending so that I grabbed the highest record that was below the parameter(otherwise for example if my sequence number was 20 it could grab 5 even though 10 was available and should be shown first. Here is the subquery I now use. Please note the actual query names m2p as T1.
IFNULL((
SELECT
M2STAT
FROM
M2P as M2P_1
WHERE
M2ON = T1.M2ON
AND M2SEQ < T1.M2SEQ
AND M2PN IN (select R1PN FROM R1P WHERE (RTWC = #WC) AND (R1SEQ = T1.M2SEQ))
ORDER BY M2SEQ DESC
FETCH FIRST ROW ONLY
), 'NULL') as PRIOR_M2STAT
Just reading your question, it looks like something I do frequently to emulate RPG READPE op codes. Is the key to M2P Order/Seq? If so, here is a basic piece that may help you build out the rest of the query.
I am assuming that you are trying to get the prior record by key using SQL. In RPG this would be like doing a READPE on the key for a file with Order/Seq key.
Here is an example using a subquery to get the status field of the prior record.
SELECT
M2ON, M2PN, M2OQ, M2STAT,
IFNULL((
SELECT
M2STAT
FROM
M2P as M2P_1
WHERE
M2P_1.M2ON = M2ON
AND M2P_1.M2SEQ < M2SEQ
FETCH FIRST ROW ONLY
), '') as PRIOR_M2STAT
FROM
M2P
Note that this wraps the subquery in an IFNULL to handle the case where it is the first sequence number and no prior sequence exists.

Get Only One Row For Each ID With the Highest Value

I have a query
SELECT
*
FROM
mgr.MF_AGREEMENT_LGR TABLE1
INNER JOIN
(SELECT
MAX(VALUE_DATE) AS VALUE_DATE,
REGISTRATION_NO AS REGISTRATION_NO
FROM
mgr.MF_AGREEMENT_LGR
GROUP BY
REGISTRATION_NO) AS TABLE2 ON TABLE1.REGISTRATION_NO = TABLE2.REGISTRATION_NO
WHERE
TABLE1.VALUE_DATE = TABLE2.VALUE_DATE
AND TABLE1.TRX_CODE = 'LCLR'
ORDER BY
TABLE1.REGISTRATION_NO
This returns the rows with the latest date for each REGISTRATION_CODE. Some have like three or more results for each REGISTRATION_CODE because it has more than one transaction on the same date.
Also, each row has its DOC_NO field.
My question is, how am I going to get only one row from each REGISTRATION_CODE with the highest DOC_NO.
By the way, DOC_NO is a varchar.
Example value for this field is: Amort 1, Amort 12, Amort 5
If those examples are in one REGISTRATION_CODE, I only need the row with the highest amort which is Amort 12.
I am using a SQL Server 2000.
SQL Server 2000 has not been supported in years. You really should upgrade to supported software.
You can get what you want with not exists:
SELECT al.*
FROM mgr.MF_AGREEMENT_LGR al
WHERE NOT EXISTS (SELECT 1
FROM mgr.MF_AGREEMENT_LGR al2
WHERE al2.registration_no = al.registration_no and
(al2.date > al2.date or
al2.date = al.date and al2.DOC_NO > al.DOC_NO
)
) AND
al.TRX_CODE = 'LCLR';
You probably want the condition on 'LCLR' in the subquery as well. However, that is not in your original query, so I'm leaving it out.

update column with numbers in sqlite table

This should be very simple but I cannot figure out how to do it. I would like to modify the values of two different columns. One from 1 to the total number of rows and the other one from the total of rows to one (basically increasing and decreasing number). I tried:
start = 0
end = number_of_rows + 1
c.execute('SELECT * FROM tablename')
newresult=c.fetchall()
for row in newresult:
start += 1
end -= 1
t = (start,)
u = (end,)
c.execute("UPDATE tablename SET Z_PK = ?", t) ---> this will transform all rows with Z_PK since there is no where statement to limit
c.execute("UPDATE tablename SET Z_OPT = ?", u)
The thing is that I don't know how I can add the "where" statement since I have no values I am sure for rows (like IDs number). A possibility would be to return the current row as the argument for "where" but I don't know how to do it...
Without an INTEGER PRIMARY KEY column, your table has an internal rowid column, which already contains the values you want:
UPDATE MyTable
SET Z_PK = rowid,
Z_OPT = (SELECT COUNT(*) FROM MyTable) + 1 - rowid