mysql unique statement - mysql

I have a table like so
ID | date | CODE
1 01-02-13 VDOT
2 03-02-13 CMAX
3 05-02-13 VDOT
1 05-02-13 CMAX
1 09-02-13 VDOT
My SQL query is as follows
SELECT * FROM Table_Name ;
Which is obviously showing all the results but I need to only show one instance of each code where the date is most recent so my result needs to look like this
1 09-02-13 VDOT
1 05-02-13 CMAX
Can anyone tell me how how to only get one result for each code (the most recent entry by date)?

SELECT a.*
FROM TableName a
INNER JOIN
(
SELECT CODE, MAX(date) max_date
FROM TableName
GROUP BY CODE
) b ON a.Code = b.Code AND
a.date = b.max_date

try this:
SELECT * FROM Table_Name
GROUP BY CODE
ORDER BY date DESC
This will ORDER after it groups. hence gives out ORDERS within the grouped-results.
.
But now try this:
SELECT * FROM
(SELECT * FROM Table_Name ORDER BY date DESC) tx2
GROUP BY CODE
This will ensure correct date ORDER before GROUP.

SELECT * FROM
TABLE AS A
JOIN
(
SELECT D.CODE, MAX(D.DATE) AS DATE FROM TABLE AS D
GROUP BY D.CODE
) AS E
WHERE
A.CODE = E.CODE
AND A.DATE = E.DATE

Related

Get latest records with id for each group with latest date-time not id - mysql

My requirement is to get id based on latest frame (based on date-time) is inserted with group by vehicle id.
I have tried with below query
select a.id,a.vehicle_id,a.info_datetime
from table_name a
join (select id, max(info_datetime) as maxdt from table_name group by vehicle_id) as b
on a.info_datetime = b.maxdt
The output will not give the proper id.
So, I want the id for latest frame inserted with group by vehicle_id.
Max(id) or Max(info_datetime) query will not give the accurate result.
SELECT id, vehicle_id FROM table_name as a WHERE info_datetime =
(SELECT MAX(info_datetime) FROM table_name as b WHERE a.vehicle_id = b.vehicle_id)
GROUP BY vehicle_id
Your attempt is almost there, but you need to join by id as well:
select a.id,a.vehicle_id,a.info_datetime
from table_name a
join (
select vehicle_id, max(info_datetime) as maxdt from table_name group by vehicle_id
) as b on a.info_datetime = b.maxdt and a.vehicle_id = b.vehicle_id
Another way to do it is to filter with a correlated subquery:
select a.*
from table_name a
where a.info_datetime = (
select max(b.info_datetime) from table_name b where b.vehicle_id = a.vehicle_id
)
Finally got the solution for above.
SELECT id, vehicle_id, info_datetime
FROM table_name
WHERE id in (
select max(m2.id) from table_name m2 group by m2.vehicle_id)
ORDER BY vehicle_id asc,info_datetime DESC
It will take approx 2 to 3 seconds to execute in around 25 lac records.

Particular MySql Query

Having the following tables
Post(*id, name, description, cat, publish_date)
Category(*id, name)
It is possible in ONE query to get (max) the first N element of each different category?
Assuming that N=3, i'd need the following result:
Result set:
["1", "Name1","Descr","cat1"]
["2", "Name1","Descr","cat1"]
["3", "Name1","Descr","cat1"]
["10","Name1","Descr","cat2"]
["20","Name1","Descr","cat2"]
["22","Name1","Descr","cat2"]
["25","Name1","Descr","cat3"]
["30","Name1","Descr","cat3"]
["19","Name1","Descr","cat3"]
And so on.
I need this, to get the first N article of EACH category, with one query (so without ask for a specific category but for all category in table)
It is possible? If yes what's the right query?
This query will do what you need. If any category has less than 3 post it will still work.
SELECT P.id,P.name,P.description,C.name
FROM Post P
LEFT JOIN Category C
ON P.type = C.id
WHERE FIND_IN_SET(P.id,
(
SELECT GROUP_CONCAT(ids) FROM
(SELECT SUBSTRING_INDEX(GROUP_CONCAT(id),',',3) as ids
FROM Post
GROUP BY type
) AS foo
GROUP BY ''
)
)
Here is a working SQL Fiddle
UPDATE
In response to your comment and updated question:
SELECT P.id,P.name,P.description,P.publish_date,C.name
FROM Post P
LEFT JOIN Category C
ON P.type = C.id
WHERE FIND_IN_SET(P.id,
(
SELECT GROUP_CONCAT(ids) FROM
(SELECT SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY publish_date DESC),',',3) as ids
FROM Post
GROUP BY type
) AS foo
GROUP BY ''
)
)
You can use UNION to join multiple queries into one. This assumes that you know what type you are selecting for each set.
SELECT * FROM
(
SELECT * FROM T1 WHERE type='Type1' ORDER BY id DESC LIMIT 3
) DUMMY1
UNION ALL
SELECT * FROM
(
SELECT * FROM T1 WHERE type='Type2' ORDER BY id DESC LIMIT 3
) DUMMY2
UNION ALL
SELECT * FROM
(
SELECT * FROM T1 WHERE type='Type3' ORDER BY id DESC LIMIT 3
) DUMMY3
The DUMMY table aliases are needed to allow ordering within each subquery.

MySql query ordering

Here is my data. I want to take 6 rows, but I want all HeadlineCategoryId's to be unique in my result list. If I select the top 6 I would take 2 rows from HeadlineCategoryID 20 (6,2). Do you have any suggestions about it?
SELECT a.*
FROM tableName a
INNER JOIN
(
SELECT HeadlineCategoryID, MAX(Creation) max_date
FROM TableName
GROUP BY HeadlineCategoryID
) b ON a.HeadlineCategoryID = b.HeadlineCategoryID AND
a.Creation = b.max_date
ORDER BY a.Creation DESC -- << specify here how are you going to sort
LIMIT 6 -- the records you want to get
UPDATE 1
SELECT a.*
FROM tableName a
INNER JOIN
(
SELECT HeadlineCategoryID, MAX(NewsID) max_id
FROM TableName
GROUP BY HeadlineCategoryID
) b ON a.HeadlineCategoryID = b.HeadlineCategoryID AND
a.NewsID = b.max_id
ORDER BY a.Creation DESC -- << specify here how are you going to sort
LIMIT 6 -- the records you want to get
It looks like you want the six most recent records, but unique by HeadlineCategoryId. If so, this will work:
select top 6 NewsId, Creation, HeadlineCategoryId
from (select t.*,
row_number() over (partition by HeadlineCategoryId order by Creation desc) as seqnum
from t
) t
where seqnum = 1
As a note . . . This question originally indicated that it was using SQL Server, not MySQL. The solution in MySQL is not as simple. Here is one method with not exists:
select NewsId, Creation, HeadlineCategoryId
from t
where not exists (select 1
from t t2
where t2.HeadlineCategoryId = t.HeadlineCategoryId and
t2.id < t.id)
limit 6
The not exists portion is saying "where there is no other record with a larger id for a given headline category".

select most recent from non-normalized data in mysql

I have a table in mysql which is not normalized and I need to query so that it groups by a certain field and gives the most recent row.
For example the table looks like
callername | callerdate | incoming | status
And I am trying to get all of the records which have their most recent status as NotAnswered and I can't figure out how you would do this, I can GROUP BY callername however I can't figure out how to get the most recent values.
Thanks.
SELECT A.* FROM
YOURTABLE A,
(
SELECT callername,callerdate,MAX(ID) AS ID
FROM YOURTABLE
WHERE status='NotAnswered'
GROUP BY callername,callerdate
) B
WHERE A.ID=B.ID;
SELECT
yourTable.*
FROM
yourTable
INNER JOIN
(
SELECT
callername,
MAX(callerdate) AS callerdate
FROM
yourTable
GROUP BY
calledname
)
AS mostRecent
ON mostRecent.callername = yourTable.callername
AND mostRecent.callerdate = yourTable.callerdate
WHERE
yourTable.status='NotAnswered'

order without duplicates

I have a table as follows:
ident_nr|proj_nr|start_time|
----------------------------
05.26.73|0000001|1116936920|
09.56.df|0000002|1213431234|
11.ac.12|0000003|1236485758|
98.er.df|0000001|1287789755|
70.12.5n|0000001|1011245554|
33.dt.vp|0000003|1239125544|
And I want a result like this:
ident_nr|proj_nr|start_time|
----------------------------
98.er.df|0000001|1287789755|
09.56.df|0000002|1213431234|
33.dt.vp|0000003|1239125544|
where proj_nr is in asc order and start time with the max value.
Note: ident_nr is unique and proj_nr could have multiple ident_nr.
Database: MySQL.
Is there an SQL query that could achieve this result?
Thanks
SELECT t.ident_nr, t.proj_nr, t.start_time
FROM YourTable t
INNER JOIN (SELECT proj_nr, MAX(start_time) AS MaxTime
FROM YourTable
GROUP BY proj_nr) q
ON t.proj_nr = q.proj_nr
AND t.start_time = q.MaxTime
ORDER BY t.proj_nr;
SELECT t1.*
FROM table AS t1
INNER JOIN (
SELECT proj_nr, MAX(start_time) AS MaxTime
FROM table
GROUP BY proj_nr) AS t2
ON (t1.proj_nr = t2.proj_nr AND t1.start_time = t2.MaxTime)
Your criteria seems to be MAX(start_time) in your sample data. If not, please be more detailed in your question about what you want.