2012-09-13 71 views
0

我在我們的日常時間記錄 中對數據進行分組和排序時出現問題以自動生成報告。 的DTR爲表結構如下:複雜的SQL排序和分組

 
Log Date Log Time Employee Name   Log Type 
9/13/2012 17:00:00 SALITA, LYNYRD ANTONIO LOGOUT 
9/13/2012 8:05:00  SALITA, LYNYRD ANTONIO LOGIN 
9/12/2012 17:05:00 SALITA, LYNYRD ANTONIO LOGOUT 
9/12/2012 8:05:00  SALITA, LYNYRD ANTONIO LOGIN 
7/10/2012 17:00:00 GARCIA, ALVIN   LOGOUT 
7/10/2012 17:00:00 AURENO, LEAH   LOGOUT 
7/10/2012 17:00:00 SALITA, LYNYRD ANTONIO LOGOUT 
7/10/2012 17:00:00 CANSINO, PAUL   LOGOUT 
7/10/2012 17:00:00 BELO, RIO    LOGOUT 
7/10/2012 17:00:00 MAG-ISA, MAYBELLE  LOGOUT 
7/10/2012 17:00:00 TARINE, KAREN   LOGOUT 
7/10/2012 17:00:00 REYES, ANDREA   LOGOUT 
7/10/2012 17:00:00 NAVARRO, KRISTINA  LOGOUT 
7/10/2012 10:30:00 MAG-ISA, MAYBELLE  LOGIN 
7/10/2012 8:00:00  SALITA, LYNYRD ANTONIO LOGIN 
7/10/2012 8:00:00  CANSINO, PAUL   LOGIN 
7/10/2012 8:00:00  BELO, RIO    LOGIN 
7/10/2012 7:40:00  AURENO, LEAH   LOGIN 
7/10/2012 7:30:00  GARCIA, ALVIN   LOGIN 
7/10/2012 7:25:00  TARINE, KAREN   LOGIN 
7/10/2012 7:10:00  NAVARRO, KRISTINA  LOGIN 
7/10/2012 7:10:00  REYES, ANDREA   LOGIN 

我想它要處理的查詢,像這樣的輸出:

 
Log Date Employee Name   LOGIN  LOGOUT 
9/13/2012 SALITA, LYNYRD ANTONIO 8:05:00  17:00:00 
9/12/2012 SALITA, LYNYRD ANTONIO 8:05:00  17:05:00 
7/10/2012 GARCIA, ALVIN   7:30:00  17:00:00 
7/10/2012 AURENO, LEAH   7:40:00  17:00:00 
7/10/2012 SALITA, LYNYRD ANTONIO 8:00:00  17:00:00 
7/10/2012 CANSINO, PAUL   8:00:00  17:00:00 
7/10/2012 BELO, RIO    8:00:00  17:00:00 
7/10/2012 MAG-ISA, MAYBELLE  10:30:00 17:00:00 
7/10/2012 TARINE, KAREN   7:25:00  17:00:00 
7/10/2012 REYES, ANDREA   7:10:00  17:00:00 
7/10/2012 NAVARRO, KRISTINA  7:10:00  17:00:00 

如何實現這一目標?

+6

Wich RDBMS:MS SQL Server,MySQL,Postgre,Oracle?而且,你有什麼嘗試?發佈一個工作查詢,不管其錯誤,也許你只是一步接近解決方案 – Yaroslav

回答

2

這是你試圖讓:

使用CASE聲明,以行轉換爲列(LoginLogout

SELECT DATE_FORMAT(LogDate, '%d/%c/%Y') AS LogDate, EmployeeName, 
    (GROUP_Concat(CASE LogType WHEN 'LOGIN' THEN LogTime END)) AS LOGIN, 
    (GROUP_Concat(CASE LogType WHEN 'LOGOUT' THEN LogTime END)) AS LOGOUT 
FROM myTable 
GROUP BY LogDate, EmployeeName 
ORDER BY LogDate desc; 

See this SQLFiddle

查詢說明)

SELECT DATE_FORMAT(LogDate, '%d/%c/%Y') AS LogDate, EmployeeName, 
    (CASE LogType WHEN 'LOGIN' THEN LogTime END) AS LOGIN, 
    (CASE LogType WHEN 'LOGOUT' THEN LogTime END) AS LOGOUT 
FROM myTable 
GROUP BY LogDate, EmployeeName, LogTime 
ORDER BY LogDate desc; 

但這會導致你喜歡in this SQLFiddle.

所以你需要使用GROUP_CONCAT(MySQL的)加入LogTimeNULLGROUP BY條款刪除LogTime

+1

thnx解決了這個問題。我只需要校準變量! thnx再次! –

+0

有沒有辦法只顯示第一次登錄和最後登錄? –

+0

@LynyrdSalita無法理解你的句子'只顯示第一次登錄和最後登錄'。你能顯示你想要的輸出嗎? – hims056

0
Select Log Date, Employee Name,  LOGIN  LOGOUT 
    case(Log Type) 
    when 'LOGIN' then Log Time AS LOGIN 
    Else 
    Log Time AS LOGOUT 
    End 
From 
YOUR_TABLE 
order by Log Date desc