I want to duplicate a specific teacher so that they appear twice in the output of a SELECT statement.
Teacher
Grade
District
Mr. Smith
3rd
West
Mrs. John
4th
South
Mr. Cameron
2nd
North
Mr. Cameron
2nd
North
Kirk Horn
1st
West
Desired result, after duplicating 'Mr. Cameron':
Teacher
Grade
District
Mr. Smith
3rd
West
Mrs. John
4th
South
Mr. Cameron
2nd
North
Mr. Cameron
2nd
North
Mr. Cameron
2nd
North
Mr. Cameron
2nd
North
Kirk Horn
1st
West
What would a SELECT statement look like - without creating a new a table?
I want to do something like this but without the INSERT:
https://dba.stackexchange.com/questions/142414/easiest-way-to-duplicate-rows
If the table is big, and the filter is not selective and backed by an index, then this "trick" avoids a second sequential scan over the table - using PostgreSQL:
SELECT t.* -- or your list of columns
FROM test t
, generate_series(1, CASE WHEN t.teacher = 'Mr. Cameron' THEN 2 ELSE 1 END);
fiddle
It's short syntax for a LATERAL join. See:
What is the difference between a LATERAL JOIN and a subquery in PostgreSQL?
fiddle
If you need more copies, just replace '2' above.
Postgres has a hard time estimating the number of rows to expect with this construct, which may confuse query planning. Stu's variant (doing the same) is slightly more expensive, but easier to estimate for query planning. Syntax needs to be adapted for Postgres:
SELECT teacher, grade, district
FROM test t
JOIN LATERAL (VALUES (1),(2)) x(v) ON v = 1 OR teacher = 'Mr. Cameron';
fiddle
You could use UNION ALL
select Teacher,Grade,District
from test
union all
select Teacher,Grade,District
from test
where Teacher='Mr. Cameron'
order by Teacher;
https://dbfiddle.uk/rBpSL8NW
If you want to force/predict how many duplicate values for Mr. Cameron you will add ,try below query which add only one duplicate value limit 1
(select Teacher,Grade,District
from test
)
union all
(
select Teacher,Grade,District
from test
where Teacher='Mr. Cameron'
limit 1
);
https://dbfiddle.uk/uUX5QD3F
Related
I want to fetch records from a table that contains duplicate records. I want the output to be like only two duplicate records from each set of duplicate records in overall record output set.
example-
Name
Country
John
India
Mark
India
Chris
Russia
Feggy
England
Rain
Russia
Monesy
Russia
Bhumi
India
Peter
England
Bruice
England
Radhe
India
Output should have only two duplicate set of records from all duplicate of similar type as we can see in output below the country is repeating only two times and it took only first two counters of duplicate records in final record set -
Name
Country
John
India
Mark
India
Chris
Russia
Feggy
England
Rain
Russia
Peter
England
You can number the lines by the window and select only the first N.
Sorting should be chosen according to the business logic of the query.
For example:
;WITH numbered_name AS
(
SELECT *
, ROW_NUMBER() OVER (PARTITION BY t.Country ORDER BY t.Name) rn
FROM table t
)
SELECT Name
, Country
FROM numbered_name
WHERE rn <= 2
Name Place visited
Ash New york
Bob New york
Ash Chicago
Bob Chicago
Carl Chicago
Carl Detroit
Dan Detroit
Above is the sample table. The output should be two names who visited place together. I.e. the output should be Ash and Bob since the places visited by Ash also visited by Bob.
Output:
Name1 Name2
Ash Bob
What is a query for this using MySQL or even relational algebra?
The simplest method is to use group_concat(). Assuming no duplicates,
select places, group_concat(names) as names
from (select name, group_concat(place order by place) as places
from t
group by name
) t
group by places
having count(*) > 1;
This will return all the names with exactly the same places on a single row. The names will be in a comma-delimited list.
This question already has an answer here:
How to output table results by using cfoutput group by date?
(1 answer)
Closed 7 years ago.
I'm working on outputting values from data base in the table. My table has 5 columns: Date, FirstName, LastName, City, State. Here is example of my data base table:
DateMeeting FirstName LastName City State
2015-12-11 Mike Johns Dallas TX
2015-12-11 John Cook Dallas TX
2015-12-11 Nick Roberts Dallas TX
2015-12-11 Oliver Ryan New York NY
2015-12-11 Michael Best New York NY
2015-12-11 David Holmes New York NY
So I want to have output table that will display just one date for multiple records. I tried to use DISTINCT on the date and that works fine but if I include my WHERE clause for City and State my query breaks. Also I tried to use GROUP BY but same problem, I can get Date values only once as long as I do not include other columns. In this case I need all columns but my Date value only once. Here is my query that I use:
Select Distinct(DateMeeting),FirstName, LastName, City, State
From Customers
Where City = 'Dallas'
and State = 'TX'
This query does not work with all columns that I have in my select, only if I run DISTINCT(DateMeeting). I would like to output my values in the table to look like this:
Date First Name Last Name City State
Mike Johns Dallas TX
John Cook Dallas TX
Nick Roberts Dallas TX
2015-12-11 Oliver Ryan New York NY
Michael Best New York NY
David Holmes New York NY
If anyone knows how this can be done please let me know. Thank you.
Each layer in the technology stack has its strengths and weaknesses.
As for mysql, do not turn it into a report engine as described with blank date columns except for one per date somewhere in the middle of a date chunk as shown. Subsequent dates as ordered will get muddled and confused.
True, one could use slightly interesting mysql variables and dump it just on the first row of a chunk. But for what.
Play to mysql's strengths, return all the data. And have the front-end (coldfusion or whatever), deal with the reporting features you desire for the output.
id points year country
-----------------------------------
1 45 1998 Mexico
2 45 2000 Germany
3 47 2010 Russia
4 45 1970 China
5 49 2010 Austria
I wonder how can I take row results considering only 2 items from country column. For example only records where country is Germany and Mexico. When I try to get results where only 1 country is criterion the thing is easy:
SELECT * FROM List WHERE Country='Mexico';
the result is:
id points year country
-----------------------------------
1 45 1998 Mexico
but when I try to get results where 2 country items are criteria problems start. I tried:
SELECT * FROM List WHERE country='Mexico' AND Country='Germany';
SELECT * FROM List WHERE country='Mexico' AND 'Germany';
SELECT * FROM List WHERE country='Mexico','Germany';
SELECT * FROM List WHERE country='Mexico'AND WHERE country='Germany';
but no desired result:
id points year country
-----------------------------------
1 45 1998 Mexico
2 45 2000 Germany
I understand that maybe I committed logical error because there is no single record where country is Mexico and Germany at same time, and sql maybe understands claim exactly that way, but, how to write correctly in sql language: Give me results for records where countries are Mexico and Germany. Thanks.
You are looking for IN operator
SELECT * FROM List WHERE Country in ('Mexico','Germany');
Just use OR.
So instead of
SELECT * FROM List WHERE country='Mexico' AND Country='Germany';
it would be
SELECT * FROM List WHERE country='Mexico' OR country='Germany';
IN is also a good function to use, especially if you've got multiple values that you want to check against but that's been covered in the other answers.
You need to use or or in, you have been using and and asking mysql to find a row where country is both Mexico and Germany which is not true.
SELECT * FROM List WHERE Country in ('Mexico','Germany');
try this:
SELECT * FROM List WHERE country='Mexico' OR Country='Germany';
SQL is using logic. Natural language is not.
When you say that you want the results for a list of countries you need to specify so. This request corresponds to an logical or. Since the name can be one or the other, both are correct.
SELECT * FROM List WHERE Country = 'Mexico' OR Country = 'Germany'
To prevent further mistakes like these, I recommend that you look up logical operations in the docs (they are very good). MySQL or the PostGres, both should be fine.
I have the following data in my database table, since I'm fairly new to MYSQL i'm having problems in querying it to give me the following output
City Subject
london english
toronto math
london math
london math
toronto english
toronto english
There can only be two subjects, english or math. Im trying to output the data this way, first the query should pick all the distinct items in the city column. Then tell me the count of each subject in that city.
output
city English Math
london 1 2
toronto 2 1
I tried grouping, but since I don't know mysql that well, I realized it just groups the subjects together and eats the cities while grouping.
try this:
SELECT city,
SUM(IF(subject='english',1,0)) AS English,
SUM(IF(subject='math',1,0)) AS Math
FROM foo
GROUP BY city;