MYSQL Merging 2 results into 1 table - mysql

Im building a c# program and am currently stuck at fetching data from MYSQL database and bind them to a grid view. I had been researching for a few days now but to no avail.
I have 4 table in the database.
table 1 - alpha
table 2 - bravo
table 3 - charlie
table 4 - delta
attributes of alpha (id, type, user, role )
attributes of bravo (id, type, date, user)
attributes of charlie (id,type, cat, doneby, comment)
atttibutes of delta (id,type, cat, doneby)
* the pk of alpha and bravo is (id)
* the pk of charlie and delta is (id, type)
i did a query1 before by inner joinning alpha, bravo and charlie which leads to the sucessful result of
(id, type, date, user, role, cat, doneby, comment)
and
i also did a query2 before by inner joinning alpha, bravo and delta which leads to the sucessful result of
(id, type, date, user, role, cat, doneby)
Right now, im trying to built a query3 which will merge the result from query1 and query2 together.
the result of my attempts leads to
(id, type, date, user, role, cat, doneby, comment,id, type, date, user, role, cat, doneby)
As i do not want the repeated columns, I would like to seek advice on how to get the result to become like the one below by placing the records as a new tuple in the result table.
(id, type, date, user, role, cat, doneby, comment)
Thanks!
P.S: the PK would not pose a problem due to (id, type)

If you want to have separate tuples, in fact union-ing the two sets, then do the following:
(select id, type, date, user, role, cat, doneby, '' as comment from yourtable1)
union
(select id, type, date, user, role, cat, doneby, comment from yourtable2)
Read more about union here.

Based in your last comment you could use the UNION then as Lajos already posted, like:
Query 1
UNION
Query 2
And for missing columns or column that could be found in either query you have to fill it with an empty one with the same column name.
See example here

Related

How to join a column of same values to another different table in SQL?

I have this table structure for names_table:
Name
Age
Gender
Someone1
25
Male
Someone2
25
Female
Another table names_with_company has this structure:
CompanyID
Name
Age
Gender
Now, I want to copy the data from names_table by adding a single value to column of CompanyID.
Expected result:
CompanyID
Name
Age
Gender
1234
Someone1
25
Male
1234
Someone2
25
Female
I am quite confused what should I include.
INSERT INTO names_with_company
'1234',SELECT * FROM names_table
or
INSERT INTO names_with_company
SELECT * FROM (
'1234'
UNION
SELECT * FROM names_table
)
These two doesn't work
I know these two tables are two different structures, but is there any way to have a static value in column and rest of the data from another table?
Also, can you please not suggest creating another table and joining them? I prefer it to be done using the above code lines, but with a working logic.
Get into the habbit of always specifying the column names:
INSERT INTO names_with_company (CompanyID, Name, Age, Gender)
SELECT 1234, Name, Age, Gender
FROM names_table;
As you can see, you can provide "literal" values for any column.
you can not able to insert because your 1st query
INSERT INTO names_with_company
'1234',SELECT * FROM names_table
is completely wrong but if you written like below
INSERT INTO names_with_company
SELECT '1234',name,age,gender FROM names_table
it will work
but it is always better to mention the column name explicitly which is given in another answer by #stu
your 2nd query also wrong cause for union operation you have to provider same number of columns for all the selection
INSERT INTO names_with_company
SELECT * FROM (
'1234'
UNION
SELECT * FROM names_table
)
but you have used only one select
write method for union operation is like below
select col1,col2 from table1
union
select col1,col2 from table2
then you can use it any other way

Making a row a column in SSRS

I am trying to make what I think is a very simple report, however I can't seem to get the result I want and I don't even know if it is possible in SSRS.
It's a list of student applicants and the courses they have applied for. Where student apply for more than 1 course, for example 3 A Levels (the maximum they apply for is 5), I want the subjects to appear in different columns rather than a list in one column. A simple table shows the report like this: 3 Columns: student ref, applications status, course(s)
I want it to look like this:
7 columns: Student ref, Application status, course1, course2, course3 etc
I have tried to use a Matrix but the best I can get is where each subject has its own column, so I have a lot of blank text boxes and a very long report as we have 50 plus courses on offer.50+ Columns: Student ref, Application status, English, Maths, Biology, sport, French etc
Assuming this will work with your database, then this should be a pretty simple solution.
A matrix is the way to go I think as as you said, if you have lots of courses with at least one application then the report will be very wide and in manageable.
So, I recreated your sample and then queried it, adding a column that calculated a 'choice number'. this 'choice number' will only ever be between 1 and 5 (based on you statement that no student applies for more than 5 subjects)
Here's the sample data and simple query beneath
DECLARE #t TABLE([Student] varchar(10), [Status] varchar(10), [Subject] varchar(20))
INSERT INTO #t
SELECT 'Stu001', 'OA', 'English' UNION
SELECT 'Stu001', 'OA', 'Maths' UNION
SELECT 'Stu002', 'OA', 'English' UNION
SELECT 'Stu002', 'OA', 'Biology' UNION
SELECT 'Stu002', 'OA', 'Sport' UNION
SELECT 'Stu003', 'OA', 'French' UNION
SELECT 'Stu003', 'OA', 'Chemistry' UNION
SELECT 'Stu003', 'OA', 'English' UNION
SELECT 'Stu004', 'OA', 'BTEC'
SELECT *
, SubjectChoiceNumber = ROW_NUMBER() OVER(PARTITION BY Student, Status ORDER BY Subject)
FROM #t
The SubjectChoiceNumber just assigns a sequential number. The sequence is sorted by the subject name.
This gives us the following output...
Now all you need to do is use a matrix control, set the column grouping to group by SubjectChoiceNumber and set the data cell expression to something like =FIRST(Fields!Subject.Value)
The report design looks like this
An the final output looks like this

SQL : Join similar tables (different column order, different field names) into one

I have 3 files containing similar information, although each file has its own format, column order, fields name...
I would like to consolidate these 3 tables into one, to be able to perform analysis on the whole table.
I tried first do to that directly by importing the files with SQL Workbench Import Wizard, assigning each field in the source file into the destination table, but that didn't work.
So now, I have imported the 3 tables in full in SQL and want to merge them.
ex.
Table 1: Date, Name, Amount, Interest Rate
Table 2: Loan Date, Loan Name, Loan Amount, Interest
Would like to merge into:
Sourcefile (indicates if data comes from Table 1 or 2),
Date Field (using Date in Table 1 or Loan Date in Table 2),
Name Field (using Name in Table 1 or Loan Name in Table 2),
Amount Field (using Amount or Loan Amount),
Interest Rate field (using Interest Rate or Interest)
Any guidance on how I can do this ?
Use a UNION to combine the two tables:
CREATE TABLE CombinedTable AS
SELECT 'Table 1' AS `source file`, date, name, amount, `interest rate`
FROM Table1
UNION ALL
SELECT 'Table 2', `loan date`, `loan name`, `loan amount`, interest
FROM Table2
You could try
Insert into table3 (srcTable, Date, Name, Amount, InterestRate)
(Select 'table1' as srcTable, Date, Name, Amount, InterestRate from Table1)
Union
(Select 'table2' as srcTable, LoanDate, LoanName, LoanAmount, Interest from Table2)
Where table3 is a new table with the specified fields

MySQL select from multiple tables that have different columns number

I'm new to MySQL so I really need some help with an issue I'm facing:
I have 7 tables in same database with some datas from tests:
The 7 tables have different columns but they all have these columns:
name.
second_name.
status.
In status are added current status of each student (accepted or rejected) and I want to display using select the name, second_name from the 7 tables where status = accepted.
I managed to display from 1 table
SELECT name, second_name FROM test1 WHERE status="accepted";
But I can not figure out how to display from all 7.
It will be a real help for me if somebody could give me a hint.
If you do not mind duplicate student names with multiple accepted tests, you can try doing it with UNION ALL:
(SELECT name, second_name FROM test1 WHERE status='accepted')
UNION ALL
(SELECT name, second_name FROM test2 WHERE status='accepted')
UNION ALL
(SELECT name, second_name FROM test3 WHERE status='accepted')
-- ...and so on
IMHO it's better to normalize database to have all the names, secondnames and statuses in the separate table and do the only select instead of UNION to improve performace.

Combining count(*) with SQL statements into one table

I have two tables in my MySQL database (table1 and table 2). I want to write a SQL query that outputs some summary stats in a nicely formatted report.
Let's for an example consider a first SQL query that takes the users over 57 year of age from the first table
SELECT count(*) AS OlderThank57
FROM table1
WHERE age >57
And from the second table we want to get the number of users that are female
SELECT count(*) AS FemaleUsers
FROM table2
WHERE gender = "female"
Now I want to have an output like the following
Number of Felame users from table 2: 514
Number of users over the age of 57 from table 1: 918
What is the best way of generating such a report?
I would offer to expand one level from Adrian's answer... return as two separate fields so you could place them separately in a report, or align / format the number, etc
SELECT 'Number of Female users from table 2:' as Msg,
count(*) as Entries
FROM table1
WHERE age >57
UNION ALL
SELECT 'Number of users over the age of 57 from table 1:' as Msg,
count(*) as Entries
FROM table2
WHERE gender = "female"
You might have to force both "Msg" columns to the same padded length, otherwise one might get truncated. Again, just another option...
You could always try the WITH ROLLUP directive when using a GROUP BY:
SELECT COUNT(*), gender FROM table1 GROUP BY gender WITH ROLLUP
If you want to get a bit crazy you can always make a series of IFs that handles the logic for one or more thing at a time:
SELECT COUNT(*) IF(gender='female', 'female', IF(age>57, 'older_than_57', '*')) AS switch FROM table1 GROUP BY switch WITH ROLLUP
SELECT CONCAT('Number of users over the age of 57 from table 1:', count(*))
FROM table1
WHERE age >57
UNION ALL
SELECT CONCAT('Number of Felame users from table 2: ', count(*))
FROM table2
WHERE gender = "female"
I don't have mysql database to check it, so you might have to cast count(*) to string.
A union is your only option if you don't have a normalized database. Your other option is to better standardize/normalize your db so you can run much more efficient queries.