1

SQLServerの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 

上記の出力を取得するためにSQLSELECTクエリを作成しようとしましたが、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 に答える