0

尝试在找到 max(DateOccurred) 的行中获取 Userid 值。我迷失在所有这些子查询中。

我正在使用 SQL Server 2008。

注意:由于是 SELECT 语句中另一个较大查询的一部分,因此需要返回单个值。

我如何获得最大日期的示例(有效);但现在我需要与此子查询最大日期关联的用户 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],
4

3 回答 3

0

我看不到您的整个查询,但您可能想改用窗口函数:

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

这可能并不完全正确。如果没有看到查询的其余部分,很难说。

获取用户 ID 将使用类似的逻辑。

编辑:

您也可以通过将其放在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
于 2013-08-08T21:20:44.183 回答
0

使用这个子查询 -


(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')) 
于 2013-08-08T21:43:03.277 回答
0

GROUP BY 子句允许您选择其他非聚合列。

我假设“用户 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 提到了另一种使用 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
于 2013-08-08T21:53:13.570 回答