Can someone please tell me how to use the group by clause, grouping by one of the keys in the table but yet having the newest timestamp at the top? I have multiple rows of data but I only want to show the newest row
If you want only the most recent one per group:
SELECT somefield
FROM table t1
WHERE timestamp = (SELECT MAX(timestamp)
FROM table t2
WHERE t1.somefield = t2.somefield);
Or just the latest most recent one:
SELECT somefield
FROM table
GROUP BY somefield
ORDER BY MAX(timestamp) DESC
LIMIT 1;
I think you're looking for the ORDER BY clause.
SELECT Foo.Bar, Foo.SomeTimestamp
FROM Foo
ORDER BY Foo.SomeTimestamp DESC
If you're grouping by a column, you're probably returning aggregate data. If the timestamp is unique for each row of aggregate data, you may need to use the MAX function (or the like) to return a single timestamp for each group. For example:
SELECT Foo.TypeID, SUM(Foo.Price) AS Price, MAX(Foo.OrderDate) AS LastOrder
FROM Foo
GROUP BY Foo.TypeID
ORDER BY MAX(Foo.OrderDate) DESC
If you only want the first row, you can use the LIMIT clause:
SELECT Foo.Bar, Foo.SomeTimestamp
FROM Foo
ORDER BY Foo.SomeTimestamp DESC
LIMIT 0, 1
This starts at row 0 and returns at most 1 row.
Related
Can anyone please help to get last record from the group.enter image description here
I think you need this:
select * from t where col = 85 order by id desc limit 1
According to your comment, this should get last records for every group: (this assumes that id is unique and "last record" means record, with highest id)
select t.* from t
inner join (select max(id) as maxid from t group by col) s
on t.id = s.maxid
To fetch the 1 row from mysql use 'limit' keyword.
MySQL supports the LIMIT clause to select a limited number of records, while Oracle uses ROWNUM.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
E.g.:
From your screenshot, subscription id is same for multiple id's you want to get last record which id is greater. The below query gets your result, grouped by subscription_id and ordered by id desc and limiting to 1 makes fetching only 1 row from database.
select * from tableName group by subscription_id order by id desc limit 1
You can used last() function.
SELECT LAST(CustomerName) AS LastCustomer FROM Customers;
When selecting data, I'm able to show how many rows were grouped from using GROUP BY by running:
SELECT id, created, COUNT(id) `count` FROM table
GROUP BY id
LIMIT 0,30
The count field easily outputs how many rows were affected by the GROUP BY. In MySQL is it possible to automatically not include any row which only has a count value of 1?
You should consider using a HAVING clause which lets you add conditions after the grouping has been done.
SELECT id, created, COUNT(id) cnt FROM table
GROUP BY id
HAVING cnt > 1
LIMIT 0,30
Another thing to mention is that the grouping might not be correct. If you group by id and you select id, created then the value for created is undetermined. MySQL will choose any of them for a given id if they differ. You might be interested in grouping by that field too or applying an aggregate function (eg: max(created)).
A second thing to mention is that COUNT(id) won't count the amount of rows but rather the amount of rows that have id not null. If id is never null then it would result in the same value as doing count(*).
Yes. You can use HAVING to limit the results of an aggregate function like COUNT (MAX,MIN,SUM, etc).
SELECT id, created, COUNT(id) `count`
FROM table
GROUP BY id
HAVING COUNT(id) > 1
LIMIT 0,30
Show the manual and find HAVING
... HAVING COUNT(id) > 1
http://dev.mysql.com/doc/refman/5.1/de/select.htmlhavinh
I have the following query:
SELECT t.ID, t.caseID, time
FROM tbl_test t
INNER JOIN (
SELECT ID, MAX( TIME )
FROM tbl_test
WHERE TIME <=1353143351
GROUP BY caseID
ORDER BY caseID DESC -- ERROR HERE!
) s
USING (ID)
It seems that I only get the correct result if I use the ORDER BY in the inner join. Why is that? I am using the ID for the join, so the order should take no effekt.
If I remove the order by, I get too old entries from the database.
ID is the primary key, the caseID is a kind of object with multiple entries with different timestamps.
This query is ambiguous:
SELECT ID, MAX( TIME )
FROM tbl_test
WHERE TIME <=1353143351
GROUP BY caseID
It's ambiguous because it does not guarantee that it returns the ID of the row where the MAX(TIME) occurs. It returns the MAX(TIME) for each distinct value of caseID, but the value of other columns (like ID) is chosen arbitrarily from members of the group.
In practice, MySQL chooses the row that it finds first in the group as it scans rows in storage order.
Example:
caseID ID time
1 10 15:00
1 12 18:00
1 14 13:00
The max time is 18:00, which is the row with ID 12. But the query will return ID 10, simply because it's the first one in the group. If you were to reverse the order with ORDER BY, it would return ID 14. Still not the row where the max time is found, but it's from the other end of the group of rows.
Your query works with ORDER BY caseID DESC because, by coincidence, your Time values increase with the increasing ID.
This sort of query is actually an error in standard SQL and most other brands of SQL database. MySQL permits it, trusting that you know how to form an unambiguous query.
The fix is to use columns in the select-list only if they are unambiguous, that is, if they are in the GROUP BY clause, then each group is guaranteed to have only one distinct value:
SELECT caseID, MAX( TIME )
FROM tbl_test
WHERE TIME <=1353143351
GROUP BY caseID
SELECT t.ID, t.caseID, time
FROM tbl_test t
INNER JOIN (
SELECT caseID, MAX( TIME ) maxtime
FROM tbl_test
WHERE TIME <=1353143351
GROUP BY caseID
) s
ON t.caseID = s.caseID and t.time = s.maxtime
You are seeing that issue because you are getting the MAX(TIME) per caseID, but since you are grouping by caseID and NOT ID, you are getting an arbitrary ID. That happens because when you use an aggregate function, like MAX, you must, for every non-grouped field in the select specify how you want to aggregate it. That means, if it's in the SELECT and NOT in the GROUP BY, you have to tell MySQL how to aggregate. If you don't then you get a RANDOM row (well, not random per se, but it's not going to be in an order that you necessarily expect).
The reason ORDER BY is working for you, is that it kind of tricks the query optimizer into sorting the results before grouping, which just so happens to produce the result you want, but be warned, that will not always be the case.
What you want is the ID that has the MAX(TIME) given a caseID. Which means your INNER join needs to connect by caseID (not ID) and time (which will give you 1 row per each 1 row in the outer table).
Barmar beat me to the actual query, but that's the way you want to go.
How can I find the most frequent value in a given column in an SQL table?
For example, for this table it should return two since it is the most frequent value:
one
two
two
three
SELECT
<column_name>,
COUNT(<column_name>) AS `value_occurrence`
FROM
<my_table>
GROUP BY
<column_name>
ORDER BY
`value_occurrence` DESC
LIMIT 1;
Replace <column_name> and <my_table>. Increase 1 if you want to see the N most common values of the column.
Try something like:
SELECT `column`
FROM `your_table`
GROUP BY `column`
ORDER BY COUNT(*) DESC
LIMIT 1;
Let us consider table name as tblperson and column name as city. I want to retrieve the most repeated city from the city column:
select city,count(*) as nor from tblperson
group by city
having count(*) =(select max(nor) from
(select city,count(*) as nor from tblperson group by city) tblperson)
Here nor is an alias name.
Below query seems to work good for me in SQL Server database:
select column, COUNT(column) AS MOST_FREQUENT
from TABLE_NAME
GROUP BY column
ORDER BY COUNT(column) DESC
Result:
column MOST_FREQUENT
item1 highest count
item2 second highest
item3 third higest
..
..
For use with SQL Server.
As there is no limit command support in that.
Yo can use the top 1 command to find the maximum occurring value in the particular column in this case (value)
SELECT top1
`value`,
COUNT(`value`) AS `value_occurrence`
FROM
`my_table`
GROUP BY
`value`
ORDER BY
`value_occurrence` DESC;
Assuming Table is 'SalesLT.Customer' and the Column you are trying to figure out is 'CompanyName' and AggCompanyName is an Alias.
Select CompanyName, Count(CompanyName) as AggCompanyName from SalesLT.Customer
group by CompanyName
Order By Count(CompanyName) Desc;
If you can't use LIMIT or LIMIT is not an option for your query tool. You can use "ROWNUM" instead, but you will need a sub query:
SELECT FIELD_1, ALIAS1
FROM(SELECT FIELD_1, COUNT(FIELD_1) ALIAS1
FROM TABLENAME
GROUP BY FIELD_1
ORDER BY COUNT(FIELD_1) DESC)
WHERE ROWNUM = 1
If you have an ID column and you want to find most repetitive category from another column for each ID then you can use below query,
Table:
Query:
SELECT ID, CATEGORY, COUNT(*) AS FREQ
FROM TABLE
GROUP BY 1,2
QUALIFY ROW_NUMBER() OVER(PARTITION BY ID ORDER BY FREQ DESC) = 1;
Result:
Return all most frequent rows in case of tie
Find the most frequent value in mysql,display all in case of a tie gives two possible approaches:
Scalar subquery:
SELECT
"country",
COUNT(country) AS "cnt"
FROM "Sales"
GROUP BY "country"
HAVING
COUNT("country") = (
SELECT COUNT("country") AS "cnt"
FROM "Sales"
GROUP BY "country"
ORDER BY "cnt" DESC,
LIMIT 1
)
ORDER BY "country" ASC
With the RANK window function, available since MySQL 8+:
SELECT "country", "cnt"
FROM (
SELECT
"country",
COUNT("country") AS "cnt",
RANK() OVER (ORDER BY COUNT(*) DESC) "rnk"
FROM "Sales"
GROUP BY "country"
) AS "sub"
WHERE "rnk" = 1
ORDER BY "country" ASC
This method might save a second recount compared to the first one.
RANK works by ranking all rows, such that if two rows are at the top, both get rank 1. So it basically directly solves this type of use case.
RANK is also available on SQLite and PostgreSQL, I think it might be SQL standard, not sure.
In the above queries I also sorted by country to have more deterministic results.
Tested on SQLite 3.34.0, PostgreSQL 14.3, GitHub upstream.
Most frequent for each GROUP BY group
MySQL: MySQL SELECT most frequent by group
PostgreSQL:
Get most common value for each value of another column in SQL
https://dba.stackexchange.com/questions/193307/find-most-frequent-values-for-a-given-column
SQLite: SQL query for finding the most frequent value of a grouped by value
SELECT TOP 20 WITH TIES COUNT(Counted_Column) AS Count, OtherColumn1,
OtherColumn2, OtherColumn3, OtherColumn4
FROM Table_or_View_Name
WHERE
(Date_Column >= '01/01/2023') AND
(Date_Column <= '03/01/2023') AND
(Counted_Column = 'Desired_Text')
GROUP BY OtherColumn1, OtherColumn2, OtherColumn3, OtherColumn4
ORDER BY COUNT(Counted_Column) DESC
20 can be changed to any desired number
WITH TIES allows all ties in the count to be displayed
Date range used if date/time column exists and can be modified to search a date range as desired
Counted_Column 'Desired_Text' can be modified to only count certain entries in that column
Works in INSQL for my instance
One way I like to use is:
select *<given_column>*,COUNT(*<given_column>*)as VAR1 from Table_Name
group by *<given_column>*
order by VAR1 desc
limit 1
I have a database table that has two fields , date and name.
I want to have my query pull the first 20 by newest date first, then the rest of the query to pull the other elements by name alphabetically.
So that way the top 20 newest products would show first, then the rest would be ordered by name.
It's a bit ugly, but you can do it in one query:
SELECT name,
`date`
FROM ( SELECT #rank := #rank + 1 AS rank,
name,
`date`
FROM (SELECT #rank := 0) dummy
JOIN products
ORDER BY `date` DESC, name) dateranked
ORDER BY IF(rank <= 20, rank, 21), name;
The innermost query, dummy, initializes our #rank variable. The next derived table, dateranked, ranks all rows by recency (breaking ties by name). The outermost query then simply re-orders the rows by our computed rank, treating ranks greater than 20 as rank #21, and then by name.
UPDATE: This query version is more compact, puts the conditional ranking logic in the outermost ORDER BY, uses IF() rather than CASE/END.
I'm afraid this has to be done by adding a special column to your table or creating a temporary table, TPup. If you let me know whether you are interested in those options, I'll tell you more.
The two queries option like the following might be a possibility, but my version of MySQL tells me LIMIT isn't available in sub-queries.
SELECT `date`, `name` from `table` ORDER BY `date` LIMIT 0, 20;
SELECT `date`, `name` from `table` WHERE `id` NOT IN (SELECT `id` from `table` ORDER BY `date` LIMIT 0, 20) ORDER BY `name`;
Use sql UNION operator to combine result of two SELECT queries.
According to MySQL docs:
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.
...
To use an ORDER BY or LIMIT clause to sort or limit the entire UNION
result, parenthesize the individual SELECT statements and place the
ORDER BY or LIMIT after the last one. The following example uses both clauses:
(SELECT a FROM t1 WHERE a=10 AND B=1)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2)
ORDER BY a LIMIT 10;
Edit:
I missed the part that explain OP needs to sort one set of the result on the date and the other set of the result alphabetically. I think you need to create a temporary field for the sorting purpose. And SQL query would be something similar to this.
(SELECT *, 'firstset' as set_id FROM t1 ORDER BY date LIMIT 0, 20)
UNION
(SELECT *, 'secondset' as set_id FROM t1 ORDER BY date LIMIT 20, 18446744073709551615)
ORDER BY
CASE
WHEN set_id='firstset' THEN date
WHEN set_id='secondset' THEN name
END DESC ;