How to get the max timestamp row from a given table - mysql

I am trying to get the max timestamp rows based of a group of software_image_build_id and variant
Here is my SQL fiddle link http://sqlfiddle.com/#!9/6ed643/1 ,it should output the max timestamp rows for a combination for software_image_build_id and variant ,I tried as follows but it is not helping,can anyone provide guidance on how to fix it?
SELECT software_image_build,MAX(timestamp) FROM software_image_builds where software_image_id=1452
group by software_image_build

You need to use inner query to get the data along with max timestamp and then using an outer query get the data by software_image_id and variant to ensure you are getting correct data with their max timestamp.
SELECT OUTSIDE.*
FROM software_image_builds OUTSIDE,
(SELECT software_image_id, variant, MAX(timestamp) as maxtimestamp
FROM software_image_builds
GROUP BY software_image_id, variant) AS INSIDE
WHERE OUTSIDE.software_image_id = INSIDE.software_image_id
AND OUTSIDE.variant = INSIDE.variant
AND OUTSIDE.timestamp = INSIDE.maxtimestamp

The result seems correct , what result do you want?
This sql get the software_image_build and the max timestamp every software_image_build.
If you want to get the max timestamp across all data ,dont't use group by.
SELECT software_image_build,MAX(timestamp) FROM software_image_builds where software_image_id=1452
If you want to get every software_image_build,and split the max timestamp every row,try the following query:
SELECT S.software_image_build,A.max_timestamp
FROM software_image_builds AS S,
(SELECT software_image_build,MAX(timestamp) as max_timestamp
FROM software_image_builds where software_image_id=1452)
AS A
group by S.software_image_build
output this :
software_image_build max_timestamp
CI_LA.UM.5.8-02200-8x98.1-16 2017-07-14T21:51:02Z
CI_LA.UM.5.8-02200-8x98.1-20 2017-07-14T21:51:02Z
CI_LA.UM.5.8-60402-8x98.1-1 2017-07-14T21:51:02Z

Try this
SELECT * FROM software_image_builds where software_image_id=1452
AND timestamp = (SELECT MAX(timestamp) as timestamp from
software_image_builds
where software_image_id=1452)
check in fiddle http://sqlfiddle.com/#!9/729532/44

The SQL you have now posted:
SELECT software_image_build,max(timestamp)
FROM software_image_builds
WHERE software_image_id=1452
GROUP BY software_image_build,variant
LIMIT 1
outputs:
software_image_build timestamp
CI_LA.UM.5.8-02200-8x98.1-16 2017-07-13T18:38:41Z
CI_LA.UM.5.8-02200-8x98.1-20 2017-07-14T21:51:02Z
CI_LA.UM.5.8-60402-8x98.1-1 2017-02-28T15:08:10Z
which appears to be exactly what you now say you wanted. If not, further clarification is required.

You can order the results by the timestamp column and then use limit to return only the first result.
SELECT software_image_build, timestamp FROM software_image_builds where
software_image_id=1452 group by software_image_build order by timestamp DESC
limit 1

select * from software_image_builds where timestamp in (SELECT MAX(timestamp)
FROM software_image_builds group by
software_image_id, variant );

Related

How do I get the SUM of a group in an sql query

My query is
SELECT *
FROM acodes
WHERE datenumber >= '2016-12-09'
GROUP BY campaignid, acode
LIMIT 0 , 30
Results are
Is there a way to SUM() the maxworth column? I want to add up all the maxworth shown above in an sql query. The answer is not SELECT *, SUM(maxworth) as there are multiple maxworth for the same acode and campaignid.
Reference the existing query as an inline view. Take the existing query, and wrap in parens, and then use that in place of a table name in another query. (The inline view will need to be assigned an alias.)
For example:
SELECT SUM(v.maxworth)
FROM (
-- existing query goes here, between the parens
SELECT *
FROM acodes
WHERE datenumber >= '2016-12-09'
GROUP BY campaignid, acode
LIMIT 0 , 30
) v
In MySQL, that inline view is referred to as a derived table. The way that query works.... MySQL first runs the query in the inline view, and materializes the resultset into a derived table. Once the derived table is populated, the outer query runs against that.
Not sure what you're asking here.
SELECT
a.MAXWORTH1,
SUM(a.MAXWORTH) AS "MAXWORTH2"
FROM (
SELECT
CAMPAIGNID,
SUM(maxworth) AS "MAXWORTH1"
FROM acodes
WHERE datenumber ='2016-12-05'
GROUP BY campaignid
) a
GROUP BY a.MAXWORTH1
This calculates the SUM() by unique campaignid, acode, and maxworth. You mention "there are multiple maxworth for the same acode and campaignid" which makes me think you might be wanting to treat "maxworth" as unique.
SELECT
campaignid,
acode,
maxworth,
SUM(maxworth) AS 'MAXWORTH1'
FROM acodes
WHERE datenumber >= '2016-12-09'
GROUP BY campaignid, acode, maxworth
Here is another attempt at answering your question.
SELECT
a.campaignid,
a.acode,
SUM(a.maxworth) as "SUMMAXWORTH"
FROM
(SELECT
*
FROM acodes
WHERE datenumber >= '2016-12-09'
GROUP BY campaignid, acode
LIMIT 0 , 30
) a
GROUP BY a.campaignid, a.acodes

SQL GROUP BY does not keep correct order by

I have a table that I am running this query on:
SELECT datetime, from_email, from_name
FROM emails
WHERE user_seq = '1'
GROUP BY from_email
ORDER BY datetime DESC
the query executes and returns data however it is not showing the data in the order of datetime DESC
When I remove the GROUP BY, the data shows in the correct order.
Looks like you are using mysql as it allows you to exclude fields from the group by clause that aren't included in an aggregate, in this case, your datetime field. Considering you want to sort the datetime descending, perhaps you really just need to use max:
SELECT max(datetime),
from_email,
from_name
FROM emails
WHERE user_seq = '1'
GROUP BY from_email, from_name
ORDER BY 1 desc
I think ,you want to group the results using from_email.. Try with the below script.. and the script is for SQL server..
;WITH cte_1
as( SELECT datetime, from_email, from_name
, ROW_NUMBER ()OVER(PARTITION BY from_email ORDER BY datetime desc) RNo
FROM emails
WHERE user_seq = '1')
SELECT datetime, from_email, from_name
FROM cte_1
WHERE RNO=1
Following code seems to work in MySql..
SELECT datetime, from_email, from_name
FROM emails e
JOIN (SELECT from_email,MAX(datetime) MaxDate
FROM emails
GROUP BY from_email)t on e.from_email=t.from_email AND e.datetime=t.MaxDate

Orderby MYSQL Syntax Wrong Data

I have a Table with a Column 'Rechnungnr' and 'Date'
Example 2016/204, 2016/202, 2016/100, 2015/12, 2016/231
and i need the last highest number. Here -> 2016/231.
SELECT * FROM TABLE Where YEAR(Date) = '2016' ORDER BY length(`Rechnungnr`) DESC LIMIT 1
But thats not working :(
Greetz, Malte
Use a combination of char_length() and the value of rechnungnr to get the max value this way:
SELECT * FROM TABLE
Where YEAR(Date) = 2016 ORDER BY char_length(`Rechnungnr`) DESC, `Rechnungnr` DESC LIMIT 1
char_length() will order the results by the number of characters within Rechnungnr field, and then within the equally long strings, we order by the value of the field itself.
Try using column name date surrounded by backtics
SELECT * FROM TABLE Where YEAR(`Date`) = '2016' ORDER BY length(`Rechnungnr`) DESC LIMIT 1
With your existing data set (if I understand the schema correctly) you can try something like this to get the day of year, cast it to an int and then sort on it:
SELECT *, CAST(RIGHT(LENGTH(`Rechnungnr`) - (INSTR(`Rechnungnr`, '/') + 1)) AS UNSIGNED) AS `DayOfYear` FROM TABLE Where YEAR(Date) = '2016' ORDER BY `DayOfYear` DESC LIMIT 1

MySQL left joining subquery to group by

I have a requirement where I need o group data into equal number ob rows. As mysql doesn't have rownum() I'm simulating this behaviour:
SET #row:=6;
SELECT MAX(agg.timestamp) AS timestamp, MAX(agg.value) AS value, COUNT(agg.value) AS count
FROM
(
SELECT timestamp, value, #row:=#row+1 AS row
FROM data
WHERE channel_id=52 AND timestamp >= 0 ORDER BY timestamp
) AS agg
GROUP BY row div 8
ORDER BY timestamp ASC;
Note: according to Can grouped expressions be used with variable assignments? this query may not be 100% correct, but it does work.
An additional requirement is to calculate the row difference between the grouped sets. I've looked for a solution joining the same table with a subquery:
SET #row:=6;
SELECT MAX(agg.timestamp) AS timestamp, MAX(agg.value) AS value, COUNT(agg.value) AS count
FROM
(
SELECT timestamp, value, #row:=#row+1 AS row
FROM data
WHERE channel_id=52 AND timestamp >= 0 ORDER BY timestamp
) AS agg
LEFT JOIN data AS prev
ON prev.channel_id = agg.channel_id
AND prev.timestamp = (
SELECT MAX(timestamp)
FROM data
WHERE data.channel_id = agg.channel_id
AND data.timestamp < MIN(agg.timestamp)
)
GROUP BY row div 8
ORDER BY timestamp ASC;
Unfortunately that errors:
Error Code: 1054. Unknown column 'agg.channel_id' in 'on clause'
Any idea how this query could be written?
You never selected channel_id from your sbuquery, so it's not returned to the parent query, and is therefore invisible. Try
SELECT MAX(agg.timestamp) AS timestamp, MAX(agg.value) AS value, COUNT(agg.value) AS count
FROM
(
SELECT timestamp, value, #row:=#row+1 AS row, channel_id
^^^^^^^^^^^^-- need this
FROM data
Since MySQL only sees and uses the fields you explicitly return from that subquery, and will NOT "dig deeper" into the table underlying the query, you need to select/return all of the fields you'll be using the parent queries.
How about this version:
SELECT MAX(agg.timestamp) AS timestamp, MAX(agg.value) AS value, COUNT(agg.value) AS count, COALESCE(prev.timestamp, 0) AS prev_timestamp
FROM (SELECT d.*, #row:=#row+1 AS row
FROM data d CROSS JOIN
(select #row := 6) vars
WHERE channel_id = 52 AND timestamp >= 0 ORDER BY timestamp
) agg LEFT JOIN
data prev
ON prev.channel_id = agg.channel_id AND
prev.timestamp = (SELECT MAX(timestamp)
FROM data
WHERE data.channel_id = agg.channel_id AND
data.timestamp < agg.timestamp
)
GROUP BY row div 8
ORDER BY timestamp ASC;
This includes all the columns in the subquery. And it puts the variable initialization in the same query.

MySQL: How to fetch all columns with distinct clause on one column with latest created record

I have a DB Table structure
id, latitude, longitude, altitude, deviceID, createdDate
I am trying to create a query which fetches the all DISTINCT deviceID which has been created at the latest..
I have tried a query
SELECT DISTINCT deviceID
FROM `devicePosition`
ORDER BY createdDate desc
Based on beiller's post, try this solution:
SELECT deviceID, createdDate
FROM `devicePosition` outer_dev_pos
WHERE createdDate = (
select max(inner_dev_pos.createdDate)
from `devicePosition` inner_dev_pos
where inner_dev_pos.deviceID = outer_dev_pos.deviceID
)
ORDER BY createdDate desc;
UPDATE: Explanation:
We are accessing the same table two times in this query, once in the outer select and once in the subselect (the inner select). Therefor, it is necessary to tell in the query which access' deviceID and createdData we mean. This is most important in the where clause of the subselect:
where inner_dev_pos.deviceID = outer_dev_pos.deviceID
If we didn't use the alias names inner_dev_pos and outer_dev_pos for the two accesses of the same table, this line would read:
where deviceID = deviceID
which obviously would not make sense.
Limit can be used in mysql to achieve this.
SELECT DISTINCT deviceID, createdDate
FROM `devicePosition`
ORDER BY createdDate desc
limit 1
Also, you can where clause
SELECT DISTINCT deviceID, createdDate
FROM `devicePosition`
WHERE createdDate = (select max(createdDate) from `devicePosition`)
SELECT MAX(deviceID) FROM `devicePosition` GROUP BY deviceID
This will select the latest as max ID is already latest and may be faster as there is not ordering.
If you're just going for the pair of deviceID and last createdDate, then use GROUP BY:
SELECT deviceID, max(createdDate)
FROM `devicePosition`
GROUP BY deviceID
ORDER BY createdDate desc;
This fetches the maximum createdDate per deviceID.