在SQL中使用单独的条件筛选列

时间:2017-03-10 18:14:52

标签: sql sql-server

我正在尝试从表中查找登录和注销时间。我能够找出登录和注销时间。

您可以看到以下链接。 Login Logout Time in SQL Server

解决方法是

    SELECT DISTINCT AGENTID, CAST(EVENTDATETIME AS date) AS [Date], 
MIN([EVENTDATETIME]) OVER (PARTITION BY [AGENTID], CAST(EVENTDATETIME AS date) ORDER BY [EVENTTYPE]) AS first_login, 
MAX([EVENTDATETIME]) OVER (PARTITION BY [AGENTID], CAST(EVENTDATETIME AS date) ORDER BY [EVENTTYPE] DESC) AS last_logout,
FROM #temp

现在我想在 EVENTTYPE = 1 过滤列 first_login EVENTTYPE = 1 last_logout 强>

你能建议一种方法吗?

1 个答案:

答案 0 :(得分:1)

caseMIN窗口函数中使用MAX表达式。

SELECT DISTINCT 
AGENTID, 
CAST(EVENTDATETIME AS date) AS [Date], 
MIN(CASE WHEN EVENTTYPE = 1 THEN [EVENTDATETIME] END) OVER(PARTITION BY [AGENTID], CAST(EVENTDATETIME AS date)) AS first_login, 
MAX(CASE WHEN EVENTTYPE = 1 THEN [EVENTDATETIME] END) OVER(PARTITION BY [AGENTID], CAST(EVENTDATETIME AS date)) AS last_logout
FROM #temp