How do I ensure, when I GROUP BY QID, that only the most recent row is returned?
ID, QID, VALUE, TIMESTAMP
45,1,Male,1362044759
58,1,Female,1362045122
59,1,Male,1362045149
60,1,Female,1362045153
82,1,Female,1362045863
83,1,Female,1362045887
92,1,Male,1362046012
101,1,Female, 1362046401
SELECT ID, QID, VALUE, TIMESTAMP FROM table GROUP BY ID
...returns the first row. I can't simply do a LIMIT 1, as this is just an example, there are lots of QIDs in the table, which are all grouped.
Thanks.
I'm assuming here you want the "latest" row for each QID. You would normally use a derived-table subquery to get each QID's latest TIMESTAMP value and then join on that:
SELECT ...
FROM myTable AS t
INNER JOIN (SELECT QID, MAX(`TIMESTAMP`) AS MaxT FROM myTable GROUP BY QID) l
ON t.QID = l.QID AND l.maxT = t.`TIMESTAMP`
This is also assuming your TIMESTAMP column increases as time goes on.
If you want the most recent record returned:
SELECT *
FROM TBL
ORDER BY `TIMESTAMP` DESC
LIMIT 1;
Otherwise, if you want to get the most recent record for each group of QID check this Stack Overflow Post that treat your same problem with optimal solutions.
You could use 'GROUP_CONCAT' in order to extract grouped data.
SELECT GROUP_CONCAT(ID ORDER BY TIMESTAMP DESC) AS latest_id
Related
I have a table where I am having duplicates value also.
From that table, I want to get the first value of duplicate values via an order by id desc.
I am using below query to find count
select product_sku, quantity
from catalog_product_store_inventory
where ax_store_id=999
ORDER BY id DESC;
From this query, I get the all duplicates value.
I hope I made my query clear.
I am very new to MySQL.
What means duplicates in your case? Duplicates according to what product_sku or both product_sku,quantity - this should be used in GROUP BY clause:
SELECT product_sku,quantity
FROM catalog_product_store_inventory c
JOIN (
SELECT MAX(id) id
FROM catalog_product_store_inventory
GROUP BY product_sku
) m ON c.id = m.id
ORDER BY id DESC means that you want last ID from group and this one is MAX.
I have two tables: ticket and ticketRules and i have a query like this:
SELECT * FROM (
SELECT * FROM ticketRules
ORDER BY
date DESC,
time DESC
) AS myTicketRules
GROUP BY ticketId
ORDER BY ticketId ASC
The first Order By (the one in the subquery) sorts data by date and time so the last ticketrule is always the first.
I group the results by ticketId so I only got the last ticketRule for each ticket.
Now I want to sort the results by ticket but if I do that the first result is also affected and tickets don't have the last ticketrule anymore but the one with the lowest id cause it's ordered by ticketId.
How can I sort only the visible records after I grouped them?
There are several issues with your query :
there should be only one ORDER BY clause (that should be placed in the outer query)
GROUP BY does not do what you think (ie it does not give access to the last ticket)
If you are trying to pull out the full latest record for each ticketId, ordered by ticketId, you can use a correlated subquery as follows :
SELECT
t.*
FROM
ticketrule t
WHERE
t.date = (
SELECT MAX(date)
FROM ticketrule
WHERE ticketId = t.ticketId
)
ORDER BY t.ticketId
you should not use a group by without aggregation function and for obtain the last value could use use an aggregation function as max( )
select ticketId, max(date)
from ticketRules
grouo by ticketId
I have four fields in my db namely
Id(auto increment),
dept_id,
mat_code,
topic
I want to retrieve the last record in the database if a condition is meet. Am using dept_id for the condition.
The normal method is to order the result in DESC order and LIMIT the result set to 1 row
SELECT Id, dept_id, mat_code, topic
WHERE dept_id = 'something'
ORDER BY Id DESC
LIMIT 1
What is the condition? For what you want, I think a subquery is necessary:
SELECT t.*
FROM (SELECT t.*
FROM t
ORDER BY Id DESC
LIMIT 1
) t
WHERE dept_id = ??;
The subquery returns the last row (based on id). The outer WHERE determines if conditions are true.
I have read many replies and to similar questions but cannot seem to apply it to my situation. I have a table that averages 10,000 records and is ever changing. It containing a column called deviceID which has about 20 unique values, another called dateAndTime and many others including status1 and status2. I need to isolate one instance each deviceID, showing the record that had the most current dateAndTime. This works great using:
select DISTINCT deviceID, MAX(dateAndTime)
from MyTable
Group By deviceID
ORDER BY MAX(dateAndTime) DESC
(I have noticed omitting DISTINCT from the above statement also yields the same result)
However, I cannot expand this statement to include the fields status fields without incurring errors in the statement or incorrect results. I have tried using IN and EXISTS and syntax to isolate rows, all without luck. I am wondering how I can nest or re-write this query so that the results will display the unique deviceID's, the date of the most recent record and the corresponding status fields associated with those unique records.
If you can guarantee that the DeviceID + DateAndTime is UNIQUE you can do the following:
SELECT *
FROM
MyTable as T1,
(SELECT DeviceID, max(DateAndTime) as mx FROM MyTable group by DeviceID) as T2
WHERE
T1.DeviceID = T2.DeviceID AND
T1.DateAndTime = T2.mx
So basically what happens is, that you do a group by on the DeviceID (NOTE: A GROUP BY always goes with an aggregate function. We are using MAX in this case).
Then you join the Query with the Table, and add the DeviceID + DateAndTime in the WHERE clause.
Side Note... GROUP BY will return distinct elements with or without adding DISTINCT because all rows are distinct by default.
Maybe:
SELECT a.*
FROM( SELECT DISTINCT *,
ROW_NUMBER() OVER (PARTITION BY deviceID ORDER BY dateAndTime DESC) as rown
FROM MyTable ) a
WHERE a.rown = 1
I am trying to do a GROUP BY statement, with the grouped by column showing the item with the newest timestamp. However, I don't think it's possible to order BEFORE a GROUP BY statement. Is the following subselect the only way to do what I'm trying to accomplish?
SELECT thread_id, content, timestamp FROM
(
SELECT thread_id, content, timestamp FROM messaging_message
ORDER BY thread_id, timestamp desc
) combined
GROUP BY thread_id
Note that for a given thread_id, there may be multiple messages associated to it, and thus multiple content and timestamps for each thread_id.
If I understand correctly and you want the most recent content per thread_id, use a MAX() aggregate to find the timestamp, and JOIN against it :
SELECT thread_id, content, timestamp
FROM
messaging_message m
JOIN (
SELECT thread_id, MAX(timestamp) AS maxts
FROM messaging_message
GROUP BY thread_id
) maxt ON m.thread_id = maxt.thread_id AND m.timestamp = maxt.maxts
The ORDER BY doesn't come into play at all by this method. It's all done by grouping.
MySQL, unlike other RDBMS doesn't strictly require you to have every SELECT column accounted for in the GROUP BY, so you could probably just do
SELECT thread_id, content, MAX(timestamp) AS maxts FROM messaging_message GROUP BY thread_id
However, that isn't portable and so I don't recommend it. Instead, the JOIN subquery returns the pair of timestamp and thread_id. Those are used to match up against the related content and any other columns you may need from the row. If you had a unique id on each row, you could also make a subquery which returns only the id for each MAX(timestamp) and use it inside an IN(). But absent that unique id, a join against the thread_id, timestamp pair does the job.