SQL子查询选择疑点

时间:2012-10-29 11:51:45

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

SQL Server中的LogTable

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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