I have 2 tables.
The 1st table have the columns fileID
, createdate
.
The 2nd table have the userid
, fileID
, createdate
as common fields along with other columns.
I am trying to write a query to find latest fileid(max)
and the 1st loaded fileid(min)
based on the createdate
for a specific userid by joining both these tables and using groupby on fileid, createdate in the query and filtering the user id in the where clause.
However the result is showing all the rows.
I need a suggestion as how to write a query inorder to get 2 records(max and min fileid records) only from both these tables and not all the records with these field changes.
I am using SQL Server to write the query.
Thanks for your help.
To select fieldid
by earliest or lattest createdate
and to have it in two separate rows you can try something like this:
SELECT fileid, "earliest" as type FROM table1 WHERE createdate = (SELECT MIN(createdate) from table1) LIMIT 1
UNION ALL
SELECT fileid, "lattest" as type FROM table1 WHERE createdate = (SELECT MAX(createdate) from table1) LIMIT 1
It is not clear, why you want to join it with the second table, but you can do it like this:
SELECT
*
FROM
(
SELECT fileid, "earliest" as type FROM table1 WHERE createdate = (SELECT
MIN(createdate) from table1) LIMIT 1
UNION ALL
SELECT fileid, "lattest" as type FROM table1 WHERE createdate = (SELECT
MAX(createdate) from table1) LIMIT 1
) as subquery1
LEFT JOIN
table2 on table2.fileid = createdate.fileid
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.