MySQL, Select, Merge tables - mysql

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?

Related

T-SQL query procedure-insert

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.

Using two columns to obtain count on another in SQL

I have a simple question that I wasn't really sure how to search for (or title!). I apologize if this has been asked a million times. For the following table, how do I generate a report that will detail the number of companies that a person has worked for and how many people have also worked for that same number? So, for example, this table should return:
people, companiesperperson
1, 1
2, 2
1, 3
for the following table called personalinfo:
id_number first last company
1 John Doe Intel
2 John Doe Microsoft
3 Phil Jenkins Amgen
4 Phil Jenkins Bayer
5 Phil Jenkins Sanofi
6 Josh Edwards Walgreens
7 Amy Dill URS
8 Amy Dill ARCADIS
Let me know if this is still confusing and if I can further clarify what I am looking to do.
Thanks!
This is a rough estimate of the query but
SELECT count as companiesperperson, COUNT(first, last) as people FROM
(SELECT COUNT(company) as count, first, last FROM personalinfo GROUP BY (first, last)) as a
GROUP BY count
To explain the query first in the subquery we are asking for the names and count of companies after splitting up all the rows by names
Then in the outer query we split up all the rows by their count and ask how many unique names can be found in each group.
There may be a few syntax errors I've left straggling but the group by feature is really what's essential to understanding how to solve this question.

sql store the data in the column wise

id user_id apt_id name value datetime
1 1 1 bp 109 ....
2 1 1 sugar 180 ....
3 2 2 bp 170 ....
I am trying to create the table in this approach because, the patient column is not the standard one, sometimes patient will be store the bp and sugar, sometime only bp.
Am i right in creating the design. If right, how to get the records of single patient.
Thanks,
If am not wrong, userid is your patientid in your scenario, in that case, use the below query to get the single patient record,
select * from Patienttable where user_id = '1'
Here you will get the single patient record. i.e., for user_id = 1
Output:
id user_id apt_id name value datetime
1 1 1 bp 109 ....
2 1 1 sugar 180 ....
Note: You can change as you want instead of 1
Others may disagree, but I wouldn't do it this way, unless you had several changing symptoms that you collect at different appointments. If it's a small collection (some of which are not collected), I would just add them as columns to the appointment table, and leave the sugar column as NULL when it's not collected.
user_id apt_id bp sugar datetime
1 1 109 180 ....
2 1 170 ....
The model you're proposing is a variant of Entity-Attribute-Value design, which has some strengths and some weaknesses. Aaron Bertrand had a good writeup of when an EAV design is useful, and what the costs are for that design. Based on the scenario you described, I don't think it's the best fit.

MySQL select distinct dateTime. Cant figure this query out

My users answer two different questions, they are added to my answers_table as one row each. I'm trying to count how many users have answered my questions which seems simple at first. Count(*) and divide by 2. YES! But: the users can add new questions as they go, so suddenly there might be three questions, all answers/3 becomes an incorrect number of users if there was two questions for a while and then three, for example!
Can anyone figure out a query for doing this? So far I've got
SELECT COUNT(DISTINCT date) as totNum FROM login_answers
But it doesn't take the time in consideration. Meaning i just get the amount of answers in total for that day, not knowing how many questions was available that day.
Here's my table:
qid is the QuestionID so i guess thats somewhere to start?
id qid answer date deviceID
1502 2 2 2012-10-19 08:42:41 7
1503 1 3 2012-10-19 08:51:53 7
1504 2 2 2012-10-19 08:51:53 7
1505 1 4 2012-10-19 09:05:23 7
1506 2 2 2012-10-19 09:05:23 7
1507 1 4 2012-10-19 09:40:59 7
My proposed solution would be to store a session Id or some auto-generated key against the answers to uniquely identify a "session" of 2, 3 or more answers from a single person.
The query would simply be
SELECT COUNT(DISTINCT session_id) totNum
FROM login_answers
With your current schema with no identifiable key, it's quite hard to answer your question correctly if at all possible.

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 :) :)