I have some data row in my table.
I want to select the Age which occurs the most.
Person | Group | Age
---
Bob | 1 | 32
Jill | 1 | 32
Shawn| 1 | 42
Jake | 2 | 29
Paul | 2 | 36
Laura| 2 | 39
Desired set:
The age that appears the most is 32.
Use the following query
select Person, count(*) as c FROM tableName GROUP BY Age
You can add the limit 1 to get the only only record and order by to get the maximum or minimum age. Use following query
select Person, count(*) as c,Age FROM profile GROUP BY Age ORDER BY c desc LIMIT 0,1
Try something like this
SELECT Person,Group,Age,MAX(field_name)
FROM table_name;
After grouping the values you can select the top 1 as below : This would select 32 as answer
SELECT TOP (1) Age
FROM tablename
GROUP BY age
ORDER BY COUNT(*) DESC
SELECT age FROM my_table GROUP BY age ORDER BY COUNT(*) DESC LIMIT 1;
Fairly obviously, in the case of a tie, this result will be misleading.
Related
Here's what I'm trying to do. Let's say I have this table t:
key_id | id | record_date | other_cols
1 | 18 | 2011-04-03 | x
2 | 18 | 2012-05-19 | y
3 | 18 | 2012-08-09 | z
4 | 19 | 2009-06-01 | a
5 | 19 | 2011-04-03 | b
6 | 19 | 2011-10-25 | c
7 | 19 | 2012-08-09 | d
For each id, I want to select the row containing the minimum record_date. So I'd get:
key_id | id | record_date | other_cols
1 | 18 | 2011-04-03 | x
4 | 19 | 2009-06-01 | a
The only solutions I've seen to this problem assume that all record_date entries are distinct, but that is not this case in my data. Using a subquery and an inner join with two conditions would give me duplicate rows for some ids, which I don't want:
key_id | id | record_date | other_cols
1 | 18 | 2011-04-03 | x
5 | 19 | 2011-04-03 | b
4 | 19 | 2009-06-01 | a
How about something like:
SELECT mt.*
FROM MyTable mt INNER JOIN
(
SELECT id, MIN(record_date) AS MinDate
FROM MyTable
GROUP BY id
) t ON mt.id = t.id AND mt.record_date = t.MinDate
This gets the minimum date per ID, and then gets the values based on those values. The only time you would have duplicates is if there are duplicate minimum record_dates for the same ID.
I could get to your expected result just by doing this in mysql:
SELECT id, min(record_date), other_cols
FROM mytable
GROUP BY id
Does this work for you?
To get the cheapest product in each category, you use the MIN() function in a correlated subquery as follows:
SELECT categoryid,
productid,
productName,
unitprice
FROM products a WHERE unitprice = (
SELECT MIN(unitprice)
FROM products b
WHERE b.categoryid = a.categoryid)
The outer query scans all rows in the products table and returns the products that have unit prices match with the lowest price in each category returned by the correlated subquery.
I would like to add to some of the other answers here, if you don't need the first item but say the second number for example you can use rownumber in a subquery and base your result set off of that.
SELECT * FROM
(
SELECT
ROW_NUM() OVER (PARTITION BY Id ORDER BY record_date, other_cols) as rownum,
*
FROM products P
) INNER
WHERE rownum = 2
This also allows you to order off multiple columns in the subquery which may help if two record_dates have identical values. You can also partition off of multiple columns if needed by delimiting them with a comma
This does it simply:
select t2.id,t2.record_date,t2.other_cols
from (select ROW_NUMBER() over(partition by id order by record_date)as rownum,id,record_date,other_cols from MyTable)t2
where t2.rownum = 1
If record_date has no duplicates within a group:
think of it as of filtering. Simpliy get (WHERE) one (MIN(record_date)) row from the current group:
SELECT * FROM t t1 WHERE record_date = (
select MIN(record_date)
from t t2 where t2.group_id = t1.group_id)
If there could be 2+ min record_date within a group:
filter out non-min rows (see above)
then (AND) pick only one from the 2+ min record_date rows, within the given group_id. E.g. pick the one with the min unique key:
AND key_id = (select MIN(key_id)
from t t3 where t3.record_date = t1.record_date
and t3.group_id = t1.group_id)
so
key_id | group_id | record_date | other_cols
1 | 18 | 2011-04-03 | x
4 | 19 | 2009-06-01 | a
8 | 19 | 2009-06-01 | e
will select key_ids: #1 and #4
SELECT p.* FROM tbl p
INNER JOIN(
SELECT t.id, MIN(record_date) AS MinDate
FROM tbl t
GROUP BY t.id
) t ON p.id = t.id AND p.record_date = t.MinDate
GROUP BY p.id
This code eliminates duplicate record_date in case there are same ids with same record_date.
If you want duplicates, remove the last line GROUP BY p.id.
This a old question, but this can useful for someone
In my case i can't using a sub query because i have a big query and i need using min() on my result, if i use sub query the db need reexecute my big query. i'm using Mysql
select t.*
from (select m.*, #g := 0
from MyTable m --here i have a big query
order by id, record_date) t
where (1 = case when #g = 0 or #g <> id then 1 else 0 end )
and (#g := id) IS NOT NULL
Basically I ordered the result and then put a variable in order to get only the first record in each group.
The below query takes the first date for each work order (in a table of showing all status changes):
SELECT
WORKORDERNUM,
MIN(DATE)
FROM
WORKORDERS
WHERE
DATE >= to_date('2015-01-01','YYYY-MM-DD')
GROUP BY
WORKORDERNUM
select
department,
min_salary,
(select s1.last_name from staff s1 where s1.salary=s3.min_salary ) lastname
from
(select department, min (salary) min_salary from staff s2 group by s2.department) s3
I have a table and I have more than 100 records in the table. I have the same records but the date of added is different.
Table is
m_id | member_id | c_k | b_k | date_of_added
1 | 101 | qwer |sdad1 | 14-02-2019 02:26:30
2 | 101 | qwe2 |sdad2 | 14-02-2019 03:30:20
3 | 102 | qweg |sdad3 | 14-02-2019 04:00:40
4 | 101 | qwe3 |sdad4 | 14-02-2019 04:30:20
5 | 102 | qweg |sdad5 | 14-02-2019 05:45:30
I tried below query but it's displaying all the records related to the member_id=101. I need a last record of the member_id.
SELECT * from m_details WHERE member_id=101 GROUP by member_id ORDER BY date_of_added DESC
My expected output is
m_id | member_id | c_k | b_k | date_of_added
4 | 101 | qwe3 |sdad4 | 14-02-2019 04:30:20
Would you help me out what is wrong with the query?
Tagging PHP team because I am working on PHP but getting the issue in query.
Use this instead :
SELECT * // Gets everything
FROM m_details // From your table
WHERE member_id=101 // For member #101
ORDER BY date_of_added DESC // Gets the last result
LIMIT 1 // Only shows that result
SELECT * from m_details
WHERE member_id=101
ORDER BY date_of_added DESC
LIMIT 1
The GROUP BY is just obscuring the result because it does not necessarily pick the data from the last row it finds.
Your query is correct. You just need to use LIMIT 1, if you need the last record:
SELECT * from m_details WHERE member_id=101 GROUP by member_id ORDER BY date_of_added DESC LIMIT 1;
SELECT * from m_details WHERE member_id=101 ORDER BY m_id DESC LIMIT 1
Using the above query for expected output. In this case, does not need to group by clause.
In MySQL 8.0, use ROW_NUMBER() :
SELECT * FROM (
SELECT t.*, ROW_NUMBER() OVER(PARTITION BY member_id ORDER BY date_of_added DESC) rn
FROM mytable t
) WHERE member_id=101 AND rn = 1
The advantage of this approach is that it will work even if you need to display the information for more than on logic, as opposite to the GROUP BY/LIMIT solution, that only works for a single user at a time.
In earlier versions of MySQL, this can also be implemented using a NOT EXISTS condition :
SELECT t.*
FROM mytable t
WHERE
t.member_id = 101
AND NOT EXISTS (
SELECT 1
FROM mytable t1
WHERE t1.member_id = t.member_id AND t1.date_of_added > t.date_of_added
)
As you want to get the only one latest record, use DESC and LIMIT = 1 as below:
SELECT * from m_details WHERE member_id = 101 ORDER BY date_of_added DESC LIMIT 1;
As member_id can have duplicate value(according to your given dataset), you can identify m_id column as unique and (auto) increasing value(it seems so) and sort based on that column in descending order to get the updated value and then just pick the first row by setting LIMIT 1. So write your query removing group by clause:
SELECT * from m_details WHERE member_id=101 order by m_id DESC LIMIT 1;
Hope, this will help.
N.B.: It seems that new entries can't have lower date_of_added value than previous as there is no specific info about that, otherwise sort by date_of_added
I have a table with these values.
I want to query this table with limit of 5 but i want total row always to be part of resultset.
Table Description:
id desc value
1 A 100
2 B 200
3 C 300
4 D 400
5 E 500
6 F 600
7 G 700
8 H 800
9 I 900
10 Total 1000
i want to know whether its possible.
Like this:
SELECT id, `desc`, value FROM table
UNION ALL
SELECT MAX(id), 'Total', SUM(value) FROM table;
However, If you need to limit the selection from the table to only 5, you have to use LIMIT inside two subqueries like so:
SELECT id, `desc`, value
FROM
(
SELECT id, `desc`, value FROM table1
ORDER BY id
LIMIT 5
) t
UNION ALL
SELECT MAX(id), 'Total', SUM(value)
FROM
(
SELECT id, `desc`, value FROM table1
ORDER BY id
LIMIT 5
) t;
For your sample data this will give you:
| ID | DESC | VALUE |
----------------------
| 1 | A | 100 |
| 2 | B | 200 |
| 3 | C | 300 |
| 4 | D | 400 |
| 5 | E | 500 |
| 5 | Total | 1500 |
SQL Fiddle Demo
Note that: The Total row will be the sum of all the previous value values, however, in your sample data it is not the total.
That's a little messy in a single query. Maybe you can use a UNION query:
SELECT `id`, `value` FROM `table` LIMIT 5
UNION
SELECT 'Total', SUM(`value`) AS `value` FROM `table`
This will yield 5 rows from the table and a 'Total' row under.
you can alternatively use WITH ROLLUP. but the downside is one column is missing: the ID.
SELECT COALESCE(`desc`, 'TOTAL') `desc`, SUM(`value`) Value
FROM Description
GROUP BY `desc`
WITH ROLLUP
SQLFiddle Demo
I have this table: I want to search by UID
ID | VID | UID
1 | 1 | 5
1 | 1 | 6
1 | 2 | 6
2 | 3 | 5
2 | 3 | 6
2 | 4 | 6
I want to end up with this result:
ID | VID | UID
1 | 2 | 6
2 | 4 | 6
In other words, only select the entries where the VID is MAX of the UID but keeping in min NID could differ. Something like this I suppose:
select * from TABLE where uid = 6 and max(vid)
???
But this doesn't work?
One way is to order by the value in descending order (so the max is at the top), then just select the first result.
SELECT t.ID,
t.VID,
t.UID
FROM table t
WHERE t.ID = 1
ORDER BY t.VID DESC
LIMIT 1
Or do you mean you want all rows where t.VID is the highest value? In which case you could do something like this,
SELECT t.ID,
t.VID,
t.UID
FROM table t
WHERE t.ID = 1
AND t.VID = (SELECT MAX(VID) FROM table);
EDIT: Based on the edit to your question, it looks like you just want the max VID value for each ID? If I'm understanding you correctly, then this should give you what you need.
SELECT t.ID,
max(t.VID) as VID,
t.UID
FROM table t
WHERE t.UID = 6
GROUP BY t.ID
You need to have a subquery. This should work:
select * from TABLE where ID='1' AND VID=(select max(VID) from TABLE)
I expect your real-life example is more complicated (at least has more data).
This query will give you the row you want.
SELECT id,vid, uid
FROM TABLE
where id = 1
and vid in (select max(vid) from TABLE where id = 1)
Hey guys, I've tried to get this right but I can't, maybe you can point me in the right direction
I have 3 columns, 'url_id', 'timestamp' and 'o'. I need to group by 'url_id' and sort by the most current timestamp.
table "example"
timestamp | url_id | o
----------------------------
2000 | 1 | 50
2007 | 1 | 70
2011 | 1 | 90
2001 | 2 | 20
2006 | 2 | 50
2009 | 2 | 40
2011 | 2 | 10
'o' is the value at the end I want. I was trying to do this with a subquery but kept getting the oldest value (tried order by, and had no luck).
What am I doing wrong? Is what I'm looking for actually require a subquery?
SELECT url_id
, MAX(timestamp) AS currentTS
FROM yourTable
GROUP BY url_id
ORDER BY currentTS DESC
Aftre you last explanation, I think you need to JOIN the above query to your original table, like this:
SELECT y.timestamp
, y.url_id
, y.o
FROM yourTable y
JOIN
( SELECT url_id
, MAX(timestamp) AS currentTS
FROM yourTable
GROUP BY url_id
) AS grp
ON grp.url_id = y.url_id
AND grp.currentTS = y.timestamp
ORDER BY y.timestamp DESC
Note: if there are two (or more) rows with same url_id and same timestamp, they'll both (or all) appear at the results.