SQL Query to add timestamp - sql

I have a Table in our ERP system that tracks the status of shop orders. It has the open date (column name ORGDUE_10) and Status column (STATUS_10) which has codes 1-6, and status 3 is an open order, status 4 is closed (the rest of the codes do not matter for this application). Unfortunately, this table does not have a timestamp column where I can get the date when the order is closed. I need to determine if multiple Shop Orders were closed (STATUS_10 changed from 3 to 4) on time or if they went past the due date (ORGDUE_10).
Any ideas how I could do a query that will accomplish this? I assume I need a another table – write the data to it and then some kind of trigger?
I am using VS2015. The Table Name that I cannot edit is Order_Master
STATUS_10 ORDNUM_10 PRTNUM_10 CURDUE_10
4 | 50015246 |ASY5670 | 9/4/2017
3 | 50016983 |ASY5699 | 5/15/2017

I figured it out (I think). Here is the code I used which seems to do the trick. this code will update, insert, and conditionally timestamp (datestamp) two different tables on two different servers. I hope this makes sense and helps someone else. I appreciate the help given #Jonathan Leffler, sorry I didn't make it easy on you.
MERGE server2.dbo.table2 AS target /* the added server.dbo is in the event the two tables are
on different sql servers*/
USING server1.dbo.table1 AS source ON (target.column-t = source.column-s) /*
column-t is the target column and column-s is the matching source column */
WHEN MATCHED AND (conditional column) AND (antoher conditional column) THEN
UPDATE SET
column-t = source.column-s, column-t (for datestamp) = (GETDATE())
WHEN NOT MATCHED AND (conditional column) AND (antoher conditional
column)THEN /* you cannot use a WHERE clause in a MERGE but you can set
up similar conditions in the WHEN statements */
INSERT (target columns)
VALUES (source columns in same order as target columns);

Related

BigQuery Create Table Query from Google Sheet with Variable item string field into Repeated Field

I hope I explain this adequately.
I have a series of Google Sheets with data from an Airtable database. Several of the fields are stringified arrays with recordIds to another table.
These fields can have between 0 and n - comma separated values.
I run a create/overwrite table SELECT statement to create native BigQuery tables for reporting. This works great.
Now I need to add the recordIds to a Repeated field.
I've manually written to a repeated field using:
INSERT INTO `robotic-vista-339622.Insurly_dataset.zzPOLICYTEST` (policyID, locations, carrier)
VALUES ('12334556',[STRUCT('recordId1'),STRUCT('recordId2')], 'name of policy');
However, I need to know how I to do this using SELECT statement rather than INSERT. I also need to know how to do this if you do not know the number of recordIds that have been retrieved from Airtable. One record could have none and another record could have 10 or more.
Any given sheet will look like the following, where "locations" contains the recordIds I want to add to a repeated field.
SHEETNAME: POLICIES
|policyId |carrier | locations |
|-----------|-----------|---------------------------------|
|recrTkk |Workman's | |
|rec45Yui |Workman's |recL45x32,recQz70,recPrjE3x |
|recQb17y |ABC Co. |rec5yUlt,recIrW34 |
In the above, the first row/record has no location Id's. And then three and two on the subsequent rows/records.
Any help is appreciated.
Thanks.
I'm unsure if answering my own question is the correct way to show that it was solved... but here is what it took.
I create a Native table in BigQuery. the field for locations is a string, mode repeated.
Then I just run an overwrite table SELECT statement.
SELECT recordId,Name, Amount, SPLIT(locations) as locations FROM `projectid.datasetid.googlesheetsdatatable`;
Tested and I run linked queries on the locations with unnest.

Add a specified # of record to MSAccess Table Automatically

Happy Holidays. I have two dependent tables, [orders] and [reviews], linked by a "one to many relationship". On the [Orders], the PK is [Order#], there is a column for [#_of_reviews_ordered]. On the [reviews] table (the PK is an auto number) the linked field is [order#] and the number of records (records on the table) should equal "[Orders].[#_of_reviews_ordered]".
Is there a simple way to accomplish this without having to do add the records to [reviews] manually?
The only way I can think to do this without VBA is fairly convoluted and would only work if your number of reviews orders fits within a finite (and reasonably small) range. For my explanation I will assume # of review will be between 0 and 3
You would need to create a table called, say, TemplateReviews. This would have at least one field called "KeyNumber", which should not actually be a key. You could also repeat as many fields as desired from Reviews, and use them to store default values for the rows to be inserted.
The important thing about TemplateReviews is that you must set it up in advance to have N rows with KeyNumber=N for each possible value of KeyNumber. For my example, we can have 0 to 3 # of reviews. So TemplateReviews will have:
0 rows with KeyNumber=0
1 row with KeyNumber=1
2 rows with KeyNumber=2
3 rows with KeyNumber=3
Once you have TemplateReviews set up, you need to create an Insert query based on it. The query will insert rows from TemplateReviews into Reviews. But you also have to filter KeyNumber to match the value on the currently selected Order, as in
=Forms!Orders![#_of_reviews]
You then need run Insert query to run using a macro triggered by a button (etc) on the Orders form. This only works the first time you click the button... but you can modify the criteria expression above to subtract the number of existing reviews, as in
=Forms!Orders![#_of_reviews] - DCount("*","Reviews","OrderId=" & Forms!Orders![order#])
Hope this helps. If you got this approach working, you could then replace the button with a single line of VBA code in the Order form AfterUpdate event to trigger the insert query.

Not Equal / Exist in Access Database

So I am unable to wrap my brain around this.
I have 2 Tables in my database with matching fields in it
Table1: ComplaintsLogged ( This table contains all the data and all records)
Table2: ComplaintsClosed (This table only contains the complaints that have been closed)
Now I am trying to run a query which can be represented something like this.
ComplaintsLogged.status - ComplaintsClosed.taskStatus
Subtract the closed status in ComplaintsClosed from ComplaintsLogged and show me the rest of the records in complaintsLogged
both have a common field of complaint No. in them.
This is one way of doing what you asked
select ComplaintsLogged.id from ComplaintsLogged
where not exists (select 1 from ComplaintsClosed
where ComplaintsClosed.id = ComplaintsLogged.id)

Update existing database values from spreadsheet

I have an existing MSSQL database where the values in some columns need updating according to a spreadsheet which contains the mappings of old data and new data.
The spreadsheet is like this:
| OLD DATA | NEW DATA |
RECORD | A | B | C | D | A | B | C | D |
1 |OLD|OLD|OLD|OLD|NEW|NEW|NEW|NEW|
2 |OLD|OLD|OLD|OLD|NEW|NEW|NEW|NEW|
Where ABCD are the column names, which relate to the database, and OLD / NEW relates to the data.
Thus for each line (approx 2500 rows)
The database values that match OLD in each column, need to be changed to NEW
My current thoughts are to do it in a similar way to this:
SQL Statement that Updates an Oracle Database Table from an Excel Spreadsheet
Essentially getting Excel to formulate a list of replace statements, though this feels like a horribly convoluted way to deal with the problem!
Is there a way to have SQL cycle though each row of the spreadsheet, check all records for a=old, b=old2, c=old3, d=old4 and then replace those values with the appropriate a=new, b=new2, c=new3, d=new4?
You shouldn't need to loop through each row in the spreadsheet. You can use the OPENROWSET command, like in the answer you linked to, to load the spreadsheet data into a sort of temporary table. You can then run a regular UPDATE statement against that table.
It would look something like this
UPDATE YourTable
SET YourTable.A = ExcelTable.NewDataA,
YourTable.B = ExcelTable.NewDataB,
YourTable.C = ExcelTable.NewDataC,
YourTable.D = ExcelTable.NewDataD
FROM YourTable
INNER JOIN OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\foldername\spreadsheetname.xls;',
'SELECT column1name, column2name, column3name, column4name
FROM [worksheetname$]') AS ExcelTable
ON YourTable.ID = ExcelTable.ID
WHERE (YourTable.A = ExcelTable.OldDataA
AND YourTable.B = ExcelTable.OldDataB
AND YourTable.C = ExcelTable.OldDataC
AND YourTable.D = ExcelTable.OldDataD)
Looks like Jeff got you the answer you needed, but for anyone looking to update a database from a Google Sheet, here's an alternative, using the SeekWell desktop app. For a version of this answer with screen shots, see this article.
Get the right rows and columns into the spreadsheet (looks like #sbozzie already had this)
Write a SQL statement that SELECT 's all the columns you want to be able update in your sheet. You can add filters as normal in the WHERE clause.
Select 'Sheets' the top of the app and open a Sheet. Then click the destination icon in the code cell and select "Sync with DB"
Add your table and primary key
In the destination inputs, add your table name and the primary key for the table.
Running the code cell will add a new Sheet with the selected data and your table name as the Sheet name. Please note that you must start your table in cell A1. It's a good idea to include an ORDER BY.
Add an action column
Add a "seekwell_action" column to your Sheet with the action you'd like performed for each row. Possible actions are:
Update - updates all columns in the row (unique primary key required)
Insert - adds the row to your database (you need to include all columns required for your database)
Sync - An Update action will be taken every time the query runs, on a schedule (see "5. Set Schedule" below)
Complete - status after the schedule has run (see below) and the actions have been taken. The new data should now be in your database. Note that 'Sync' actions will never show complete, as they run every time the schedule runs. To stop a 'Sync' action, change it manually.
Set Schedule
To execute the actions, select the clock icon at the top of the application, indicate the frequency and exact time, and click 'Save.' You can manage your schedule from the inserted 'RunSheet' (do not delete this sheet or you will need to reset your schedule) or from seekwell.io/profile. If you need to run the actions immediately, you can do so from /profile.
Gotchas
You need to start your table in cell A1.
Snowflake column names are case sensitive. Be sure to respect this when specifying the primary key, etc.
If your server is behind a firewall, you will need to whitelist SeekWell's static IP address to use scheduling. See more about whitelisting here.

Update all rows of a single column

I'm dealing with two tables which have 2 columns, as listed under.
Table 1: table_snapshot
account_no | balance_due
Table 2: table_ paid
account_no | post_balance | delta_balance
I added a third column to table2 with the following command:
ALTER TABLE table_paid ADD delta_balance number(18);
I'm trying to use the following query, to update the new column ( delta_balance ) with the difference in balances between 1 and 2.
FYI, table_paid is a subset of table_snapshot. i,e., table 2 has only a few accounts present in table 1. I get an error saying : SQL Statement not properly ended. the query i'm using is:
UPDATE table_paid
SET table_paid.delta_balance = table_paid.post_balance - table_snapshot.balance_due
from table_paid, table_snapshot
WHERE table_paid.account_no = table_snapshot.account_no;
Appreciate if someone can correct my query.
Many thanks.
novice.
Oracle doesn't have the UPDATE ... FROM syntax that you're using from MS Sql Server (which, I believe, isn't ANSI anyway). Instead, when you need to do an update on a result set, Oracle has you create the resultset as a kind of inline view, then you update through the view, like so:
UPDATE ( SELECT tp.delta_balance
, tp.post_balance
, ts.balance_due
FROM table_paid tp
JOIN table_snapshot ts
ON tp.account_no = ts.account_no
)
SET delta_balance = post_balance - balance_due;
This is more "correct" than the answers supplied by Babar and palindrom, as their queries will update every row in table_paid, even if there are no corresponding rows in table_snapshot. If there is a 1-1 correspondance, you don't need to worry, but it's safer to do it with the inline view.
It's unclear from your example which table is the parent table, or (as I'm guessing) neither is the parent table and account_no is pointing to the primary key of another table (presumably account, or "table_account" by your naming conventions). In any case, it's clear that there is not a 1-1 correspondence in your table - 15K in one, millions in the other.
This could mean 2 things: either there are many rows in table_snapshot that have no corresponding row in table_paid, or there are many rows in table_snapshot for each row in table_paid. If the latter is true, your query is impossible - you will have multiple updates for each row in table_paid, and the result will be unpredictable; how will you know which of the "post_balance - balance_due" expressions will ultimately determine the value of a given delta_balance?
If you run my query, you will find this out quickly enough - you will get an error message that says, "ORA-01779: cannot modify a column which maps to a non key-preserved table". This error will appear based not on the data in the table (it may be okay), but based on the primary keys you have defined on the two tables. If the join condition you specify doesn't unambiguously result in a 1-1 relationship between the updated table and the rest of the join, based on the defined keys, you will get this error. It's Oracle's way of telling you, "You're about to screw up your data".
In the other answers here, you will only get an error (in that case, ORA-01427: single-row subquery returns more than one row) if you actually have data that would cause a problem; my version is more strict, so it may turn out that you will need to use the other versions.
And, as the others have said, you'll definitely want an index on account_no for the table_snapshot table. One on the table_paid wouldn't hurt either.
Try this
UPDATE table_paid
SET table_paid.delta_balance = table_paid.post_balance -
(SELECT table_snapshot.balance_due from table_snapshot WHERE table_paid.account_no =
table_snapshot.account_no);
UPDATE table_paid
SET table_paid.delta_balance = table_paid.post_balance - ( select balance_due from table_snapshot
WHERE table_paid.account_no = table_snapshot.account_no )