1

SQL Server 中的日志表

timestamp                  user_name     session_id
2012-10-17 06:30:10        Sanjay        034A955F
2012-10-17 06:30:20        Sanjay        034A955F
2012-08-20 13:20:59        John          0547961A 
2012-08-20 13:21:05        John          0547961A 
2012-08-20 13:22:10        John          0547961A 
2012-10-17 04:02:10        John          0977661B 

期望的输出

user       Total_login      This_Month_Login   Recent_Login  
Sanjay     2                2                  2012-10-17 06:30:10 
John       4                1                  2012-10-17 04:02:10 

我试图编写 SQL SELECT 查询来获得以上输出,但我不擅长 SQL,所以不能提前写,只写了 2 列。你能帮我得到上面的选择输出吗?

select user_name as 'User', count (distinct session_id) as 'Total_Login' 
from "LogTable" 
group by user_name
4

3 回答 3

2
DECLARE
  @this_month DATETIME
SELECT
  @this_month = DATEADD(MONTH, DATEDIFF(MONTH, 0, getDate), 0)

SELECT
  user_name,
  COUNT(*)                                                  AS total_log,
  SUM(CASE WHEN timestamp >= @this_month THEN 1 ELSE 0 END) AS log_this_month,
  MAX(timestamp)                                            AS recent_login
FROM
  "LogTable"
GROUP BY
  user_name
于 2012-10-29T11:54:29.067 回答
0

试试这个查询

select
    T.user_name as User,
    count(distinct T.session_id) as Total_Login,
    count(distinct case when datediff(mm, T.timestamp, getdate()) = 0 then session_id else null end) as This_Month_Login,
    max(T.timestamp) as Recent_Login
from LogTable as T
group by T.user_name

我假设您只需要在输出中计算不同的 session_id。如果你没有,那么你需要

select
    T.user_name as User,
    count(*) as Total_Login,
    count(case when datediff(mm, T.timestamp, getdate()) = 0 then 1 else null end) as This_Month_Login,
    max(T.timestamp) as Recent_Login
from LogTable as T
group by T.user_name
于 2012-10-29T11:53:48.083 回答
0

试试这个

Select 
    USER_NAME, 
    COUNT(*) As Total_login,
    COUNT(case when MONTH(getdate())=MONTH(tm) then 1 end) As This_Month_Login,
    MAX(tm) as Recent_Login
From MyTable
group by user_name 
order by user_name desc
于 2012-10-29T12:01:16.257 回答