简体   繁体   中英

sql - select different value of a max value nested query

Trying to obtain the Userid value in a row where the max(DateOccurred) was found. I'm getting lost in all these sub-queries.

I'm using SQL Server 2008.

NOTE: Need to return single value since part of another larger query in a SELECT statement.

Example of how I obtain max date (which works); but now I need the userid associated with this subquery max date.

    (

    SELECT MAX(LC.[Date]) 

    FROM table_LC LC LEFT JOIN table_LM LM ON LC.[c] = LM.[c] AND LC.[L] = LM.[L]

    WHERE LM.[c] = LC.[c] AND LM.[L] = LC.[L] AND LC.[LC] = 'ABCDEF'

    ) as [ABCDEF_Date],

I cannot see your whole query, but you probably want to use a window function instead:

max(case when lc.lc = 'ABCDEF' then lc.[DATE] end) over () as maxdate

This may not be exactly right. It is hard to say without seeing the rest of the query.

Getting the user id would use similar logic.

EDIT:

You can also get the same effect by putting this in the from clause (it is not correlated):

from . . . cross join
     (select top 1 lc.[Date], lc.id
      FROM table_LC LC LEFT JOIN
           table_LM LM
           ON LC.[c] = LM.[c] AND LC.[L] = LM.[L]
      WHERE LM.[c] = LC.[c] AND LM.[L] = LC.[L] AND LC.[LC] = 'ABCDEF'
      order by lc.[date] desc
     ) as ABCDEF_Date

Use this sub query -


(SELECT Userid,
        Date
FROM   (SELECT Userid, Date FROM table_LC) b
WHERE  date = (SELECT MAX(LC.[Date]) 
FROM table_LC LC LEFT JOIN table_LM LM ON LC.[c] = LM.[c] AND LC.[L] = LM.[L]
WHERE LM.[c] = LC.[c] AND LM.[L] = LC.[L] AND LC.[LC] = 'ABCDEF')) 

A GROUP BY clause lets you SELECT additional non-aggregated columns.

I assumed the "user ID" field is in the LC table, but it could just as easily be in the LM table.

SELECT
    LC.[UserID]
    , MAX(LC.[Date]) 

FROM
    table_LC LC
    LEFT JOIN table_LM LM ON 
        LC.[c] = LM.[c] AND LC.[L] = LM.[L]

WHERE LM.[c] = LC.[c] AND LM.[L] = LC.[L] AND LC.[LC] = 'ABCDEF'

GROUP BY LC.[UserID]

@Gordon mentioned another good approach using SELECT TOP 1 combined with ORDER BY.

SELECT TOP 1
    LC.[UserID]
    , LC.[Date]

FROM
    table_LC LC
    LEFT JOIN table_LM LM ON 
        LC.[c] = LM.[c] AND LC.[L] = LM.[L]

WHERE LC.[LC] = 'ABCDEF'

ORDER BY LC.[Date] DESC

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM