T-SQL query procedure-insert - mysql

I am wondering if any of you would be able to help me. I am trying to loop through table 1 (which has duplicate values of the plant codes) and based on the unique plant codes, create a new record for the two other tables. For each unique Plant code I want to create a new row in the other two tables and regarding the non unique PtypeID I link any one of the PTypeID's for all inserts it doesnt matter which I choose and for the rest of the fields like name etc. I would like to set those myself, I am just stuck on the logic of how to insert based on looping through a certain table and adding to another. So here is the data:
Table 1
PlantCode PlantID PTypeID
MEX 1 10
USA 2 11
USA 2 12
AUS 3 13
CHL 4 14
Table 2
PTypeID PtypeName PRID
123 Supplier 1
23 General 2
45 Customer 3
90 Broker 4
90 Broker 5
Table 3
PCreatedDate PRID PRName
2005-03-21 14:44:27.157 1 Classification
2005-03-29 00:00:00.000 2 Follow Up
2005-04-13 09:27:17.720 3 Step 1
2005-04-13 10:31:37.680 4 Step 2
2005-04-13 10:32:17.663 5 General Process
Any help at all would be greatly appreciated

I'm unclear on what relationship there is between Table 1 and either of the other two, so this is going to be a bit general.
First, there are two options and both require a select statement to get the unique values of PlantCode out of table1, along with one of the PTypeId's associated with it, so let's do that:
select PlantCode, min(PTypeId)
from table1
group by PlantCode;
This gets the lowest valued PTypeId associated with the PlantCode. You could use max(PTypeId) instead which gets the highest value if you wanted: for 'USA' min will give you 11 and max will give you 12.
Having selected that data you can either write some code (C#, C++, java, whatever) to read through the results row by row and insert new data into table2 and table3. I'm not going to show that, but I'll show how the do it using pure SQL.
insert into table2 (PTypeId, PTypeName, PRID)
select PTypeId, 'YourChoiceOfName', 24 -- set PRID to 24 for all
from
(
select PlantCode, min(PTypeId) as PTypeId
from table1
group by PlantCode
) x;
and follow that with a similar insert.... select... for table3.
Hope that helps.

Related

MySQL how to update aggregated table (based on another table) automatically? [duplicate]

This question already has answers here:
How do I create a view in MySQL? [closed]
(2 answers)
Closed last month.
I have a table (table1) in a MySQL database with data similar to this:
Category
total_sold
revenue
profit
fruit
32
200
150
veggies
12
50
23
chips
23
170
110
fruit
43
300
180
chips
5
25
15
New data is inserted into the table regularly through a python script using sqlalchemy (appends csv files to the mysql table using Pandas).
I want to create an aggregated table (table2) based on category using a query, and I want the aggregation to update whenever I add new records to the table1.
For example after executing the query:
CREATE TABLE table2 AS
SELECT Category, AVG(total_sold) avg_sold, AVG(revenue) avg_revenue, AVG(profit) avg_profit
FROM table1
GROUP BY 1
I get table2 as:
Category
avg_sold
avg_revenue
avg_profit
fruit
37.5
250
165
veggies
12
50
23
chips
14
97.5
62.5
Now if I insert several new records to table1, how can I make table2 update automatically? (recalculate all aggregations based on all table1 records including the newly added ones)
I read about creating a trigger, but I'm not sure how to execute it or if it would work in a case like this.
I Would appreciate any help.
MySQL does not support "materialized views". You have to do the aggregation yourself. Build a separate Summary Table and keep it updated. A simple IODKU is one way to do that maintenance; the link discusses other, such as a nightly batch update of the day's data.

Nested sort in SELECT followed by Conditional INSERT based upon results of SELECT inquiry

I have been struggling with the following for some time.
The server I am using has MySQL ver 5.7 installed.
The issue:
I wish to take recorded tank level readings from one table, find the difference between the last two records for a particular tank, and multiply this by a factor to get a quantity used.
The extracted quantity, if it is +ve, else 0 , then to be inserted into another table for further use.
The Quant value extracted may be +ve or -ve as tanks fill and empty. I only require the used quantity -ie falling level.
The two following tables are used:
Table 'tf_rdgs' sample;
value 1 is content height.
id
location
value1
reading_time
1
18
1500
2
18
1340
3
9
1600
4
18
1200
5
9
1400
6
18
1765
yyyy
7
18
1642
xxxx
Table 'flow' example
id
location
Quant
reading_time
1
18
5634
dd-mm: HH-mm
2
18
0
dd-mm: HH-mm
3
18
123
current time
I do not require to go back over history and am only interested in the latest level readings as a new level reading is inserted.
I can get the following to work with a table of only one location.
INSERT INTO flow (location, Quant)
SELECT t1.location, (t2.value1 - t1.value1) AS Quant
FROM tf_rdgs t1 cross join tf_rdgs t2 on t1.reading_time > t2.reading_time
ORDER BY t2.reading_time DESC limit 1
It is not particularly efficient but works and gives the following return from the above table.
location
Quant
18
123
for a table with mixed locations including a WHERE t1.location = ... statement does not work.
The problems i am struggling with are
How to nest the initial sorting by location for the subsequent inquiry of difference between the last two tank level readings.
A singular location search is ok rather than all tanks.
A Conditional INSERT to insert the 'Quant' value only if it is +ve or else insert a 0 if it is -ve (ie filling)
I have tried many permutations on these without success.
Once the above has been achieved it needs to run on a conditional trigger - based upon location of inserted data - in the tf_rdgs table activated upon each new reading inserted from the sensors on a particular tank.
I can achieve the above with the exception of the conditional insert if each tank had a dedicated table but unfortunately I cant go there due existing data structure and usage.
Any direction or assitance on parts or whole of this much appreciated.

MySQL, Select, Merge tables

I have a little problem that I can´t solve. It´s really simple, but I just can´t figure it out and have search some time but not found any good answers.
I have two tables:
Transaction
t_nr (Primary) a_nr quantity
1 1 10
2 2 10
Customer
c_nr (PRIMARY) name city
1 Mario Tokyo
2 Luigi Beijing
And want to insert values from the two above into another table with one query looking
Account
a_nr (primary) c_nr
Problem is that when just making a regular select-from-statement it returns:
a_nr c_nr
1 1
1 2
2 1
2 2
i.e. not just merges them together in the account table.
a_nr c_nr
1 1
2 2
How do I do this?
Does a_nr correlate to c_nr (are they equal)?
If so,
insert into account (a_nr,c_nr)
SELECT transaction.a_nr, customer.c_nr from transaction, customer
WHERE transaction.a_nr = customer.c_nr
Although this seems completely pointless to only insert two values that are the same.
What is the desired output of Account?

MS Access 2007 Rows to columns in recordset

I have a table which is like a questionnaire type ..
My original table contains 450 columns and 212 rows.
Slno is the person's id who answer the questionaire .
SlNo Q1a Q1b Q2a Q2b Q2c Q2d Q2e Q2f .... Q37c <450 columns>
1 1
2 1 1
3 1
4 1 1
5 1
I have to do analysis for this data , eg Number of persons who is male (Q1a) and who owns a boat (Q2b) i.e ( select * from Questionnaire where Q1a=1 and Q2b=1 ).. etc .. many more combinations are there ..
I have designed in MS access all the design worked perfectly except for a major problem ( Number of table columns is restricted to 255 ).
To be able to enter this into access table i have inserted in as 450 rows and 212 columns (now am able to enter this into access db). Now while fetching the records i want the record set to transpose the results into the form that i wanted so that i do not have to change my algorithm or logic .... How to achieve this with the minimum changes ? This is my first time working with Access Database
You might be able to use a crosstab query to generate what you are expecting. You could also build a transpose function.
Either way, I think you'll stil run into the 255 column limit and MS Access is using temporary table, etc.
However, I think you'll have far less work and better results if you change the structure of your table.
I assume that this like a fill-in-the-bubble questionnaire, and it's mostly multiple choice. In which case instead of recording the result, I would record the answer for the question
SlNo Q1 Q2
1 B
2 B
3 A
4 A C
5 A
Then you have far fewer columns to work with. And you query for where Q1='A' instead of Q1a=1.
The alternative is break the table up into sections (personal, career, etc.) and then do a join, and only show the column you need (so as not to exceed that 255 column limit).
An way to do this that handles more questions is have a table for the person, a table for the question, and a table for the response
Person
SlNo PostalCode
1 90210
2 H0H 0H0
3
Questions
QID, QTitle, QDesc
1 Q1a Gender Male
2 Q1b Gender Female
3 Q2a Boat
4 Q2b Car
Answers
SlNo QID Result
1 2 True
1 3 True
1 4 True
2 1 True
2 3 False
2 4 True
You can then find the question takers by selecting Persons from a list of Answers
select * from Person
where SlNo in (
select SlNo from Answers, Questions
where
questions.qid = answers=qid
and
qtitle = 'Q1a'
and
answers.result='True')
and SlNo in (
select SlNo from Answers, Questions
where
questions.qid = answers=qid
and
qtitle = 'Q2a'
and
answers.result='True')
I finally got the solutions
I created two table one having 225 columns and the other having 225 column
(total 450 columns)
I created a SQL statement
select count(*) from T1,T2 WHERE T1.SlNo=T2.SlNo
and added the conditions what i want
It is coming correct after this ..
The database was entered wrongly by the other staff in the beginning but just to throw away one week of work was not good , so had to stick to this design ... and the deadly is next week .. now it's working :) :)

MySQL SELECT query - one cell to multiple rows

In MySQL I have one particular cell with data something like this
5,6,7,8,9
If I need to search for specific 2 numbers one after another I do a query with LIKE statement for those 2 particular numbers. For ex. I need to check if there's a row with numbers 6 & 7 *in a row* I do
SELECT * FROM table WHERE column LIKE '%,6,7,%' OR column LIKE '%,6,7' OR column LIKE '6,7,%'
It's little redundant and clumsy. If I 'convert' those numbers into multiple rows, for ex. every number would become it's own row with column 'numbers' ordered with 'sort' column so I know the order of rows.
id numbers sort
55 8 4
56 6 2
57 5 1
58 7 3
59 9 5
...
What's the identical query for this case? So I would have the same result as with the query above. I need to order the query with sort column and check if the numbers 6,7 are occurring one after another with that sorting.
Should be something like this. (if I understood right your problem). It will return nothing if the 2 numbers are not in sequence by the sort column.
select *
from table t1
join table t2 on t1.sort=t2.sort+1
where t1.numbers=6 and t2.numbers=7
if you do not know which one should be first you can use it like this:
select *
from table t1
join table t2 on t1.sort=t2.sort+1 or t1.sort+1=t2.sort
where t1.numbers=6 and t2.numbers=7
Are the numbery always incremented by one or can they have any value?
I'm proposing the following table structure
id col1 col2 rowid
1 1 2 1
2 2 3 1
3 1 4 2