MySQL Householding: Group Duplicate Addresses And Update Names to Include Both People - mysql

If we assume that I already have a query that presented me with the data I want in a very simple way for a mailer: Name, Address, City, State, Zip. But if the file's around 20k, there are a decent amount of people who have the exact same address.
Obviously it's simple to do a GROUP BY Address to remove any duplicates. But the problem I'm running into is not being able to update the names to include both people for a mailer.
If this is two rows in the original data:
Name Address City State Zip
Jerry Seinfeld 129 West 81st Street New York NY 10024
Elaine Benes 129 West 81st Street New York NY 10024
I would like the query output to result in one row where the name looks like this:
Name Address City State Zip
Jerry Seinfeld & Elaine Benes 129 West 81st Street New York NY 10024
And if we want to get fancier, it would be great if they also had the same last name to include something for that in the script so that if both of their last names were "Seinfeld," the output would be:
Name Address City State Zip
Jerry & Elaine Seinfeld 129 West 81st Street New York NY 10024
So generally, I'm just looking for some SELECT *-type query that households these addresses but also includes something to update the names. Thanks!

Below Query would work well, Self tested:
SELECT
IF(COUNT(T1.Address) = (SELECT COUNT(DISTINCT T2.Last) FROM t1 T2 WHERE T2.Address = T1.Address), GROUP_CONCAT(T1.First," ",T1.Last SEPARATOR ' & '), CONCAT(GROUP_CONCAT(T1.First SEPARATOR ' & '), ' ',T1.Last)) Name
FROM t1 T1
GROUP BY T1.Address

GROUP_CONCAT()
Examples here: https://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

Related

Putting one line per name using SQL

I have this sql output that gives me different row for the same person based on their location. I wanted one line per person and three columns with a Y if they lived there.
Select name, Paris, London, NYC from location
Name Paris London NYC
John y
John y
John y
I want this
Name Paris London NYc
John y y y
you can use max function :
select name, max(paris), max(london), max(nyc) from location
group by name
SELECT name,
IF(SUM(IF(Paris='y',1,0)>0,'y','') as Paris,
IF(SUM(IF(London='y',1,0)>0,'y','') as London,
IF(SUM(IF(NYC='y',1,0)>0,'y','') as NYC
FROM location
GROUP BY name
Side-note, the database is not designed optimally! 3 tables with Name, Cities and Location with proper joins would be much more efficient.
Use Subselects like:
Select name,
(SELECT Paris FROM location WHERE name = a.name),
(SELECT London FROM location WHERE name = a.name)
FROM location a
This way you make a Select in an Select, and link the subselect to the name of the overlaying select.
Some of the other users told you to use aggregations.
In the most database systems an aggregation query is less efficient than a subquery, so you should use aggregations with care.

SQL query to get state,then city and address and zip

I'm trying to get data from database in this format:
state
|__city
| |__address
| |__zip
I want all unique states and cities with all addresses and zip codes concatenated.
Here's what I've tried:
SELECT
state,
GROUP_CONCAT('(',address,';)') AS address,
GROUP_CONCAT('(',zip,';)') AS zip
FROM location
WHERE
sername='ABC#gmail.com'
GROUP BY state,city
UPDATE
There is problem with concatenation. I want the data in this format:
state city address zip
Karnataka BANGALORE (sdbsbd);(dsdsds); NULL
and I'm getting data as
state city address zip
Karnataka BANGALORE (sdbsbd);,(dsdsds); NULL
I don't want the comma in the address:
;,
I think you need the SEPERATOR argument in the GROUP_CONCAT() function.
https://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
SELECT state, GROUP_CONCAT('(',address,';)' SEPARATOR '') as
address,GROUP_CONCAT('(',zip,';)' SEPARATOR '') as zip FROM location Where
username='ABC#gmail.com' GROUP BY state,city"

MySQL Query to display records from table

I have a query.I have table with two columns country and state.I want to display columns in following format
Country State
----------- ---------
India Delhi
Bangalore
Kolkata
Mumbai
USA California
Florida
Las Vegas
Virginia
It means "India" just appear one time in country column and and repeated values would come as blank value in country column when i select country and state from table.
Thanks in advance
Presentation is usually if not always better done outside of SQL so I'd recommend doing this in whatever your presentation layer runs, but if it's a requirement for the query, you can do it using session variables;
SELECT Country, State FROM (
SELECT IF(Country=#country, '', Country) Country, State, #country := Country
FROM (SELECT Country, State FROM Table1 ORDER BY Country, State) dummy1,
(SELECT #country:='') dummy2
) dummy3;
An SQLfiddle to test with.
Just to show a (probably) better way, you can use this to get a list of states per country, and process it further in your presentation layer;
SELECT Country, GROUP_CONCAT(State) FROM Table1 GROUP BY Country;
Another SQLfiddle.
use pl/sql.Moreover your table would be voilating 5th normal form.

Eliminate duplicate rows using MySQL DISTINCT

I have a world db. The table below was generated with:
SELECT *
FROM geolocations
WHERE city = 'Santa Cruz'
The table contains multiple entries for each city, it once contained a Zip Code field.
I want to delete duplicate entries for cities. I tried using:
CREATE TABLE tmp
SELECT DISTINCT city, region
FROM geolocations
The previous statement eliminates the duplicate entries, but how do I get id and other fields to copy to new table?
-----------------------------------------------------------------------
id Country Region City Latitutde Longitude
-----------------------------------------------------------------------
4683 US CA Santa Cruz 37.0447998047 -122.1020965576
5748 US CA Santa Cruz 36.9712982178 -121.9875030518
9506 US CA Santa Cruz 37.0101013184 -122.0324020386
11205 US CA Santa Cruz 37.0344009399 -121.9796981812
11379 US CA Santa Cruz 36.9898986816 -122.0603027344
13146 US CA Santa Cruz 37.0101013184 -122.0324020386
14362 US CA Santa Cruz 37.0101013184 -122.0324020386
30055 BO 03 Santa Cruz -12.2833003998 -66.2500000000
31760 ES 59 Santa Cruz 42.6666984558 -2.3499999046
39477 AR 22 Santa Cruz -27.6667003632 -64.2667007446
-----------------------------------------------------------------------
As Marvo said those are not duplicate rows perse but some fields duplicated. The best approach could be to redesign your database and break that table into two -at least-. This could serve you as a starting point:
First create a table that contains different-uniques- cities:
CREATE TABLE city SELECT DISTINCT city FROM db
Add a primary key to that table:
ALTER TABLE city ADD id_city INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
Create a table that contains all your records and the id of the corresponding city that each record belongs to:
CREATE TABLE records SELECT db.id,db.country, db.region, city.id_city, db.lat,db.long FROM db INNER JOIN city ON db.city = city.city
You can make another one for cities asocciated with countries if you wish.
This query worked I wanted to select distinct city, region combinations and group it with its associated data in the new table.
CREATE TABLE clean_gls SELECT * FROM geolocations GROUP BY city, region;
IN MSSQL it's this"
SELECT distinct City, Region
INTO tmp
FROM geolocations
WHERE City = 'Santa Cruz'
In MYSQL, you can use select into table
Although I havent tested it, something like this should work:
INSERT INTO tmp(City, Region)
SELECT distinct City, Region
FROM geolocations WHERE WHERE City = 'Santa Cruz'

MySQL: Export all rows with the same column data into same file

Say you have a large table with thousands of rows and 3 columns, looking something like this:
Name City Birthyear
Egon Spengler New York 1957
Mac Taylor New York 1955
Sarah Connor Los Angeles 1959
Jean-Luc Picard La Barre 2305
Ellen Ripley Nostromo 2092
James T. Kirk Riverside 2233
Henry Jones Chicago 1899
Jason Bourne Paris 1971
......
and so on. Is it possible to sort people by City into separate files?
For example, if you have 100 or more cities in the table, is there a query that would create 100 or more files with people names and birth years in it? For a smaller number of cities one could use
-e "select Name, Birthyear from Table where City = New York" > NewYork.csv
and so on for each city in the table.
But it's not fun to do it manually if you have hundreds of cities.
From the sick and wrong department (may contain syntax errors, this is just to give you an idea of the twisted possibilities):
SELECT concat("SELECT name, birthyear from table where city = '",
city,
"' into outfile '",
city,"';")
FROM table
Put that in query1.sql, then:
mysql < query1.sql > query2.sql
mysql < query2.sql
Write a query that generates queries on the fly, then execute the resulting queries against the database. This definitely falls into the "quick and dirty" category.
Note also that the queries execute on the MySQL server, which could be a different box than where you're executing the MySQL client. If so, you'll need some way at getting at the resulting files. If you don't have shell access to the server, this could be a problem unless there is a network file system that the server can write to that you can read from another host.
I think your best bet would be to write a little script that does a SELECT DISTINCT on each column and uses the results to write the querys of the form you suggest.
You could also put "select Name, Birthyear from Table order by City" into a csv, then use a small script (Perl or something) to split the file where the name in the city column changes. Anyway, probably impossible without some external scripting.