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.
Related
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
I am trying to retrieve the the first row among the duplicate row, THE FIRST OCCURED ***
--Table--
Order_No Product User
1 Book Student
2 Book Student
3 Book Student
I want to get the Order_No of the first duplicate row in JAVA, I have used DISTINCT and DISTINCT TOP 1 etc but nothing worked, NEED HELP
SELECT min(order_no), product, user
FROM 'table'
GROUP BY user, product
This is basic SQL?
SELECT min(order_no), product, user FROM table GROUP BY product, user
See also more information on GROUP BY
All fields not part of your group by must have some sort of way to determine which to pick of the n potentially different values. min() will pick the lowest value (even with strings and dates) while max() will pick the highest. You can also use First() and Last() to grab the value according to when they show up.
Supposing you had other values to pick from, you might see something like:
SELECT min(order_no), product, user, min(creation_date),
sum(quantity), first(billing_address)
FROM orders GROUP BY product, user
SELECT t.*
FROM table t
WHERE NOT EXISTS ( SELECT a
FROM table t2
WHERE t2.Product = t.Product
AND t2.User = t.User
AND t2.Order_No < t.Order_No
)
I have a Table containing columns Email, Ip, State, City, TimeStamp, Id
I need to count where Email and IP are distinct, group by State
So when I run a MYSQL query,
select State, City ,count(distinct( Email )), count(DISTINCT( IP))
from table
group by Stat, City
It gives me distinct of each, but not AND
I need a count of distinct Email && Distinct IP ; grouped by State, City.
And distincts cant be within the Group, it has to be the 1st instance of EMAIL, and first instance of IP in entire database. So if i expand it, and add a date parameter, even though im selecting a specific date, I still can check whole database for the uniques.
So if i need
select state, city, count ( distinct ( IP ) , count ( distinct ( EMAIL ))
from table
where timestamp > date(2014-12-01)
group by state, city
What type of query is this? And how can I accomplish this?
My gut tells me i need to do CONCAT as suggested, but also another select inside. So select whole database distinct ip, then select that specific criteria from the other select.
This can help a bit to have a "distinct(A && B)"
SELECT DISTINCT(CONCAT(A,'_',B)),C,D
FROM table
GROUP BY C,D
We struggled to do this on a production server and found the query required was too resource intensive. So we created a table with an update on first instance the item occurs, then we check for counts with a join like so:
select count(a.State) from tablename A
inner join table_update U
on a.id = u.id
WHERE a.parameters..
and c.first_email = 1
and c.first_ip = 1
We couldnt find a single table that wouldnt bring our server down with 400,000 records. Its not a classy answer, but its what we had to use.
I want to select result from different database based on a subsring value from columns.
Here is my table student:
Original_student Other_student
1010173 1240240
1010173 1240249
The 3rd digit in the number will be used to distinguish database. for example. I want the query be
select original_student, Other_student, month
from student join database-(substring(other_student,3,1).payment
My question is: How can I concatenate the substring to a database name or column name dynamically?
Thanks
Supposing you have a field to identify each student by a unique id (id_student), here is a cheap alternative:
CREATE OR REPLACE VIEW v_student_payment AS
SELECT 0 AS db, payment, id_student FROM database-0
UNION
SELECT 1 AS db, payment, id_student FROM database-1
UNION
SELECT 2 AS db, payment, id_student FROM database-2
UNION
SELECT 3 AS db, payment, id_student FROM database-3
/* here you have to add all databases you're using. There's a little maintenance cost, for if one day there's a new database to be created this view would have to be modified */
;
SELECT
original_student,
Other_student,
month,
v.payment
FROM
student s
JOIN v_student_payment v ON v.id_student = s.id_student AND v.db = SUBSTRING(other_student,3,1)
Did you try using a Case statement for checking with the join. Try looking at this link
Use Case Statement in Join
I am trying to select a small number of records in a somewhat large database and run some queries on them.
I am incredibly new to programming so I am pretty well lost.
What I need to do is select all records where the Registraton# column equals a certain number, and then run the query on just those results.
I can put up what the db looks like and a more detailed explanation if needed, although I think it may be something simple that I am just missing.
Filtering records in a database is done with the WHERE clause.
Example, if you wanted to get all records from a Persons table, where the FirstName = 'David"
SELECT
FirstName,
LastName,
MiddleInitial,
BirthDate,
NumberOfChildren
FROM
Persons
WHERE
FirstName = 'David'
Your question indicates you've figured this much out, but are just missinbg the next piece.
If you need to query within the results of the above result set to only include people with more than two children, you'd just add to your WHERE clause using the AND keyword.
SELECT
FirstName,
LastName,
MiddleInitial,
BirthDate,
NumberOfChildren
FROM
Persons
WHERE
FirstName = 'David'
AND
NumberOfChildren > 3
Now, there ARE some situations where you really need to use a subquery. For example:
Assuming that each person has a PersonId and each person has a FatherId that corresponds to another person's PersonId...
PersonId FirstName LastName FatherId...
1 David Stratton 0
2 Matthew Stratton 1
Select FirstName,
LastName
FROM
Person
WHERE
FatherId IN (Select PersonId
From Person
WHERE FirstName = 'David')
Would return all of the children with a Father named David. (Using the sample data, Matthew would be returned.)
http://www.w3schools.com/sql/sql_where.asp
Would this be any use to you?
SELECT * from table_name WHERE Regestration# = number
I do not know what you have done up to now, but I imagine that you have a SQL query somewhere like
SELECT col1, col2, col3
FROM table
Append a where clause
SELECT col1, col2, col3
FROM table
WHERE "Registraton#" = number
See SO question SQL standard to escape column names?.
Try this:
SELECT *
FROM tableName
WHERE RegistrationNo = 'valueHere'
I am not certain about my solution. I would propose You to use view. You create view based on needed records. Then make needed queries and then you can delete the view.
View description: A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database.
Example:
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
For more information: http://www.w3schools.com/sql/sql_view.asp