选择将相同的列按日期分组到不同的列中

时间:2016-01-22 13:06:56

标签: sql sql-server sql-server-2008

我有一个登录表,如下所示:

Created                |  Action
20/01/2016 08:00:00 AM    login
20/01/2016 10:05:10 AM    logout
20/01/2016 12:00:00 PM    login
20/01/2016 04:12:22 PM    logout
21/01/2016 08:00:50 AM    login
21/01/2016 09:44:42 AM    login
21/01/2016 10:44:42 AM    login
21/01/2016 04:00:42 PM    logout

我需要选择一个如下所示的结果集:

Created        |    Login   |    Logout        
20/01/2016      08:00:00 AM   04:12:22 PM
21/01/2016      08:00:50 PM   04:00:42 PM

以下是我的尝试:

SELECT
    CONVERT(VARCHAR(10),li.Created,10) [Date],
    CONVERT(VARCHAR(8),MAX(li.Created),8) [Login],
    CONVERT(VARCHAR(8),MAX(lo.Created),8) [Logout]
FROM Logins li
LEFT JOIN Logins lo ON lo.[Action] = 'logout'
GROUP BY li.Created

但结果并未按日期分组。

什么是正确的方法?

3 个答案:

答案 0 :(得分:3)

您可以尝试这样:

SELECT 
CONVERT(VARCHAR(10),li.Created,10) [Date], 
CONVERT(VARCHAR(8),MAX(li.Created),8) [Login],
CONVERT(VARCHAR(8),MAX(lo.Created),8) [Logout] 
From Logins li 
Left Join Logins lo  on lo.[Action] = 'logout' 
GROUP BY CAST(li.Created AS DATE)

即,您需要按日期对记录进行分组,而不是按日期和时间进行分组。

答案 1 :(得分:2)

我将假设你的结果中20日凌晨4点的注销是一个疏忽,否则我们需要知道确定它应被视为当天注销时间的逻辑。

一个问题是,您尝试仅将日期显示为您的群组,但您按日期和时间进行分组。

请改为尝试:

SELECT
    CAST(LI.created AS DATE) AS created,
    MIN(CAST(LI.created AS TIME)) AS login,
    MAX(CAST(LO.created AS TIME)) AS logout
FROM
    dbo.My_Table LI
LEFT OUTER JOIN dbo.My_Table LO ON
    LO.action = 'logout' AND
    CAST(LO.created AS DATE) = CAST(LI.created AS DATE)
WHERE
    LI.action = 'login'
GROUP BY
    CAST(LI.created AS DATE)

另一件需要考虑的事情是登录期是否可以跨越日期边界。如果这是在科技行业,那么登录1/20 10pm并注销1/21凌晨2点并不奇怪。 ;)

答案 2 :(得分:1)

与Rahul的答案类似,但您可以自行加入以获得首次登录/上次登出,并按日期分组以获得您要求的结果;

SELECT CONVERT(DATE,     li.created)  [Date], 
       CONVERT(TIME, MIN(li.created)) [Login],
       CONVERT(TIME, MAX(lo.created)) [Logout] 
FROM Logins li 
JOIN Logins lo 
  ON CONVERT(DATE, li.created) = CONVERT(DATE, lo.created)
 AND li.action = 'login'
 AND lo.action = 'logout' 
GROUP BY CONVERT(DATE, li.created)

An SQLfiddle to test with

编辑:对于SQL Server 2005未​​经测试,您可能需要为varchars设置长度;

SELECT CONVERT(VARCHAR, li.created, 110)    [Date], 
       CONVERT(VARCHAR, MAX(li.created), 8) [Login],
       CONVERT(VARCHAR, MAX(lo.created), 8) [Logout] 
FROM Logins li 
JOIN Logins lo 
  ON CONVERT(VARCHAR, li.created, 110) = CONVERT(VARCHAR, lo.created, 110)
 AND li.action = 'login'
 AND lo.action = 'logout' 
GROUP BY CONVERT(VARCHAR, li.created, 110)

Another SQLfiddle