简体   繁体   English

sql-选择最大值嵌套查询的其他值

[英]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. 尝试在找到max(DateOccurred)的行中获取Userid值。 I'm getting lost in all these sub-queries. 我在所有这些子查询中迷路了。

I'm using SQL Server 2008. 我正在使用SQL Server 2008。

NOTE: Need to return single value since part of another larger query in a SELECT statement. 注意:由于SELECT语句中另一个较大查询的一部分,需要返回单个值。

Example of how I obtain max date (which works); 我如何获取最大日期的示例(有效); but now I need the userid associated with this subquery max date. 但现在我需要与此子查询的最大日期关联的用户ID。

    (

    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: 我看不到您的整个查询,但您可能想改用window函数:

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子句中来获得相同的效果(它不相关):

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. GROUP BY子句使您可以选择其他未聚合的列。

I assumed the "user ID" field is in the LC table, but it could just as easily be in the LM table. 我假设“用户ID”字段位于LC表中,但它也很容易位于LM表中。

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. @Gordon提到了将SELECT TOP 1与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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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