Table name: Offices
CompanyID OfficeLocation
01 USA
01 Africa
03 USA
04 USA
04 Israel
04 Germany
05 Africa
I need to get CompanyID that have most records in this table (04 for table above)
I tried:
SELECT CompanyID
GROUP BY CompanyID
HAVING COUNT(*) = (
SELECT COUNT (*) FROM EntitySite
GROUP BY CompanyID
ORDER BY COUNT(*) DESC
)
Dsnt work at all(
You can use next simple query:
SELECT CompanyID, COUNT(OfficeLocation) CountOfficeLocation
FROM EntitySite
GROUP BY CompanyID
ORDER BY CountOfficeLocation DESC
LIMIT 1;
MySQL query online
Firstly, question is abstract, data has no obvious relation (different id's have different countries), no know requirement what id is considered when counting (first, last or random).
However, here is query from what I get, this will return most common first and least common last.
SELECT CompanyID
FROM
(
SELECT count(*) as c,
CompanyID
FROM Offices
GROUP BY CompanyID
) T
ORDER BY c desc
Related
Imagine I have the following table with the following data already inserted in it:
Table Person
id_person name age
------------------------------------------
1 name1 18
2 name2 37
3 name3 23
Now imagine I want to execute a query that shows the persons older than 30 and persons younger than 20 and I want to use an UNION clause, like this:
select name, age from person
where age >= 30
UNION
select name, age from person
where age <= 20;
The output this query would give would be:
name age
-------------------
name2 37
name1 18
But what if I want to order the output using an order by clause?
Where should I write the clause?
Would any of the following queries work?
select name, age from person
where age >= 30
group by name
order by age asc
UNION
select name, age from person
where age <= 20;
...
select name, age from person
where age >= 30
UNION
select name, age from person
where age <= 20
group by name
order by age asc;
Your last query (although age is ambiguous in the select list since it is not included in the group by clause):
select name, age from person
where age >= 30
UNION
select name, age from person
where age <= 20
group by name
order by age asc;
is the same as:
(select name, age from person
where age >= 30)
UNION
(select name, age from person
where age <= 20
group by name)
order by age asc;
as it is explained in the documentation:
A statement without parentheses is equivalent to one parenthesized...
So the order by clause affects the result of the UNION.
Also it is important to know that:
Use of ORDER BY for individual SELECT statements implies nothing about
the order in which the rows appear in the final result because UNION
by default produces an unordered set of rows
so don't use ORDER BY in neither of the 2 queries (if you don't want to set a LIMIT also), but use one at the end for the final result.
Your queries are malformed -- columns in the a group by query that are neither keys or aggregated. However, the general idea in MySQL is to use parentheses:
(<query 1>)
union all
(<query 2>)
order by <whatever>
Your particular query can be written as:
select name, age
from person
where age >= 30 or age <= 20
order by age asc;
I have a table called 'customers':
id | name | age
1 | john | 35
2 | paul | 22
3 | ana | 26
4 | mark | 19
5 | jack | 29
i want to select the name and max age, the name and min age... something like:
john 35 mark 19
is it possible?
The below query will give you the min and max on one row as requested. If there are multiple matches for min/max you will get multiple rows. Depending on the SQL engine you use, the syntax to limit to one row is different.
SELECT cMax.Name, cMax.Age, cMin.Name, cMin.Age
FROM customers cMin
JOIN customers cMax ON
cMax.Age = (SELECT MAX(Age) FROM customers)
WHERE cMin.Age = (SELECT MIN(Age) FROM customers)
There are different types of joins (e.g. INNER, OUTER, CROSS); however, for your question it doesn't much matter which you use.
Yes, you can do it,
select name, age from customers
where age in (select max(age)
from customers union select min (age)from customers)
try this
select name, age from customers where age=(select max(age) from customers) union
select name, age from customers where age=(select min(age) from customers)
If you want them on the same row:
select cmin.*, cmax.*
from (select name, age as minage
from customers
order by age asc
fetch first 1 row only
) cmin cross join
(select name, age as maxage
from customers
order by age desc
fetch first 1 row only
) cmax;
fetch first 1 row only is standard syntax for returning only the first row of the result set. Some databases have bespoke syntax, such as limit or select top (1).
Try using this query to show MAX age:-
select * from customers where age=(select max(age) from customers);
To show MIN age use the below Query:-
select * from customers where age=(select min(age) from customers);
You could use a cross join, which will put the two query ouputs next to one another. Building off Rodrigo's queries:
select
max_cust.name,
max_cust.age,
min_cust.name,
min_cust.age
from (select name, age from customers where age=(select max(age) from customers)) as max_cust
cross join (select name, age from customers where age=(select min(age) from customers)) as min_cust
It's maybe not the most performant but it gets the right shape. Be wary of cross joins when the tables don't have exactly 1 row, as it creates a cartesian product of the rows in the tables being joined.
I'm trying to run a query that returns distinct AddressIDs.
The row to be retuned for each AddressID should be the one with the latest ReadDate.
I also want to return the value from (non-aggregate) columns PhoneNumber, SomeCode, and Country for the given records.
There are similar questions on here to mine, but nothing seems to suit my exact situation. I've tried different subqueries and making the other columns aggregates, but I can't seem to get the results I desire.
Say the base of the query like:
select cr.AddressID, cr.ReadDate, in.PhoneNumber, in.SomeCode, in.Country
from CustomerReadings cr, in.CustomerInfo
where cr.AddressID = in.AddressID
For example, if I have a table that looks like:
AddressID ReadDate PhoneNumber SomeCode Country
1005 01/01/1997 5556565 GHS Canada
1005 05/06/2006 5556753 ROT USA
1005 08/12/2018 5552345 JKR USA
2007 02/05/2012 5558746 MSC Canada
2007 12/07/2018 5552345 RRE France
4000 03/01/1999 5552345 RRE France
4000 09/05/2007 5551243 MSR USA
I want the query results to look like:
AddressID ReadDate PhoneNumber SomeCode Country
1005 08/12/2018 5552345 JKR USA
2007 12/07/2018 5552345 RRE France
4000 09/05/2007 5551243 MSR USA
If anything is unclear please let me know and I'll update my question accordingly.
In the case of 1 table as you used in your answer example, the code works.
But when I bring in another table, I no longer get just one distinct AddressID back, eg:
select (or select distinct)
cr.AddressID, cr.ReadDate, in.PhoneNumber, in.SomeCode, in.Country
from
CustomerReadings cr,
CustomerInfo in
where
cr.AddressID = in.AddressID
and cr.ReadDate =
(select max(cr2.ReadDate)
from CustomerReadings cr2
where cr2.AddressID = cr.AddressID)
order by
2 desc,
1;
There should be questions that are very similar. I use a correlated subquery:
select t.*
from t
where t.readdate = (select max(t2.readdate) from t t2 where t2.addressid = t.addressid);
You need correlated subquery :
select t.*
from table t
where readdate = (select max(t1.readdate) from table t1 where t1.addressid = t.addressid);
If you are working with latest version of MySQL, then row_number() would helpful :
select t.*
from (select t.*,
row_number() over (partition by addressid order by readdate desc) as seq
from table t
) t
where seq = 1;
However, if the readdate has ties, then row_number() would no longer help use dense_rank() instead.
I have a table of flights, which have an origin and destination city, represented as a foreign id.
A very simplified example of this table looks like:
id | origin | destination
023 1 3
044 3 2
332 2 1
509 1 3
493 1 4
I need to get the first time that a city shows up as an origin or a destination; a list of all the flights that contain a city that hasn't been flown to or from yet.
What I would like to get for the above example would be:
023: 1, 3
044: 2
493: 4
Flights 332 and 509 aren't in the output because they only visit cities that have already been visited.
Here's what I've tried:
(SELECT distinct(origin), distinct(destination) FROM flights ORDER BY id)
Doesn't work because you can't select more than one distinct column
SELECT (distinct(origin) FROM flights ORDER BY id) UNION (distinct (destination) FROM flights ORDER BY id)
Doesn't work because of syntax errors, but mainly because it doesn't take into account that a city should be unique in the origin and destination columns.
If there's not a quick way to do this in SQL I'm also happy to just iterate through and keep track of cities that have been visited (this app has literally one user, and he doesn't care about a few milliseconds of computation because he's over 80), but I'd love to know just so that I can learn more about SQL!
This does it:
SELECT id, GROUP_CONCAT(city ORDER BY city) cities
FROM (
SELECT city, min(id) id
FROM (
SELECT origin city, MIN(id) id
FROM flights
GROUP BY city
UNION
SELECT destination city, MIN(id) id
FROM flights
GROUP BY city) u
GROUP BY city) x
GROUP BY id
DEMO
I have a table which stores IDs and the city where the store is located.
I want to list all the stores starting with the stores that are in the city where there are the most stores.
TABLE
ID CITY
1 NYC
2 BOS
3 BOS
4 NYC
5 NYC
The output I want is the following since I have the most stores in NYC, I want all the NYC location to be listed first.
1 NYC
4 NYC
5 NYC
2 BOS
3 BOS
SELECT count(City), City
FROM table
GROUP BY City
ORDER BY count(City);
OR
SELECT count(City) as count, City
FROM table
GROUP BY City
ORDER BY count;
Ahh, sorry, I was misinterpreting your question. I believe Peter Langs answer was the correct one.
This one calculates the count in a separate query, joins it and orders by that count (SQL-Fiddle):
SELECT c.id, c.city
FROM cities c
JOIN ( SELECT city, COUNT(*) AS cnt
FROM cities
GROUP BY city
) c2 ON ( c2.city = c.city )
ORDER BY c2.cnt DESC;
This solution is not a very optimal one so if your table is very large it will take some time to execute but it does what you are asking.
select c.city, c.id,
(select count(*) as cnt from city c2
where c2.city = c.city) as order_col
from city c
order by order_col desc
That is, for each city that you come across you are counting the number of times that that city occurs in the database.
Disclaimer: This gives what you are asking for but I would not recommend it for production environments where the number of rows will grow too large.
SELECT `FirstAddressLine4`, count(*) AS `Count`
FROM `leads`
WHERE `Status`='Yes'
AND `broker_id`='0'
GROUPBY `FirstAddressLine4`
ORDERBY `Count` DESC
LIMIT 0, 8