尝试在找到max(DateOccurred)的行中获取Userid值。我迷失在所有这些子查询中。
我正在使用SQL Server 2008。
注意:需要返回单个值,因为SELECT语句中的另一个较大查询的一部分。
我如何获得最大日期(有效)的示例;但现在我需要与此子查询最大日期关联的用户标识。
(
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],
答案 0 :(得分: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
答案 1 :(得分: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'))
答案 2 :(得分: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